Compare hours to determine if new date

Viewed 51

I am working on an app where the user can set sample frequency between 1 - 8 hours, adjusted to closest full hour, to collect and process data.

Example-1, frequency set to 8 hour and starts @ 06:00:

06:00 -> 14:00 -> 22:00 -> 06:00 (add day)

Example-2, frequency set to 3 hour and starts @ 20:00:

20:00 - > 23:00 -> 02:00 (add day) -> 05:00

Example-3, frequency set to 3 hour and starts @ 08:00 = no problem with date change:

08:00 - > 11:00 -> 14:00 -> 17:00

I use the following format on the sample date-time "yyyy-MM-ddTHH:00:00Z" but the only date that is generated is current date meaning I need to add a day when crossing midnight.

My problem is that I have not figured out the logic how to determine, if required, when crossing over to the next date without to much spagetti code? ...given that the date change can happen in any of samples 2 - 4.

And then tried to determine but failed.

Any help would be appreciated.

2 Answers
void Main()
{
    string[] hours = {"06:00", "14:00", "22:00", "06:00"};
    var baseDate = DateTime.Today;
    
    for (int i = 0; i < hours.Length; i++)
    {
        var mins = TimeSpan.Parse(hours[i]).TotalMinutes;
        if (i > 0 && mins < TimeSpan.Parse(hours[i - 1]).TotalMinutes) 
           baseDate = baseDate.AddDays(1);

        var dt = baseDate.AddMinutes(mins);
        Console.WriteLine(dt);
    }
}

You didn't tell us what you really need. Code could be simpler just adding the differences.

You can simply compare the value of the Date properties of the first DateTime and the second DateTime (created by adding the frequency value to the first one). If they're different, you've crossed into a new day:

public static void Main()
{
    var start = DateTime.Now;
    var frequency = 8;

    for (int i = 0; i < 10; i++)
    {
        var  next = start.AddHours(frequency);
        Console.Write("start hour: " + start.Hour + " -> next hour: " + next.Hour);
        if (!start.Date.Equals(next.Date)) Console.Write(" (crossed over to next day)");
        Console.WriteLine();
        start = next;
    }

    Console.ReadKey();
}

Output:

start hour: 11 -> next hour: 19
start hour: 19 -> next hour: 3 (crossed over to next day)
start hour: 3 -> next hour: 11
start hour: 11 -> next hour: 19
start hour: 19 -> next hour: 3 (crossed over to next day)
start hour: 3 -> next hour: 11
start hour: 11 -> next hour: 19
start hour: 19 -> next hour: 3 (crossed over to next day)
start hour: 3 -> next hour: 11
start hour: 11 -> next hour: 19
Related