citm09 citm09 - 3 months ago 16
ASP.NET (C#) Question

How to divide time range in intervals if Start Time is greater than End time

I'm accepting time range from user in a 24 hr clock format.My code below works if the start time is less than End time. The following code divides the given time range with the interval.

How should I deal with a situation where Start Time is less than End Time. E.g. If Start Time is say 21:00 (9 PM) and End time is 03:00 (3 AM). Any idea how should I divide the time range where Start time is MORE than End Time?

DateTime start = DateTime.ParseExact(txtStartTime.Text.Trim(),"HH:mm", null);
DateTime end = DateTime.ParseExact(txtEndTime.Text.Trim(), "HH:mm", null);

int interval = Convert.ToInt32(txtSessionDuration.Text.Trim());
for (DateTime i = start; i < end; i = i.AddMinutes(interval))
{
//some code goes here...
}

Answer

Assuming that there is no user error and user want to get intervals, when end time is less than start time.

As DateTime contains not only time component, but date component, so we can simply add one day if end time is less than start time. You should modify you code as follows:

    DateTime start = DateTime.ParseExact(txtStartTime.Text.Trim(),"HH:mm", null);
    DateTime end = DateTime.ParseExact(txtEndTime.Text.Trim(), "HH:mm", null);
    if (end < start)
    {
        end = end.AddDays(1);
    }

    int interval = Convert.ToInt32(txtSessionDuration.Text.Trim());
    for (DateTime i = start; i < end; i = i.AddMinutes(interval)) 
    {
           //some code goes here...
    }

After you have parsed DateTime from string - both start and end contains equals date component. This mean that end time is earlier than start time. But if you passing end time, that is less than start time, you actually mean, that end time is time of next day.

So, if time component of end is less than it of start you can simply add 1 day to end and you will have ability to iterate from start to end.