Sathish
Sathish

Reputation: 419

How to find overlapping hours of a timerange and a date range?

I have a time range 11:00 PM to 5:00 AM. (night hours range)

I have date range for eg., 2014-04-01 00:00:00 to 2014-04-02 23:59:59

Now I need to calculate how many night hours are present in the given date range.

For the above example it should return 11 hours 59 minutes 59 seconds

Explanation:

2014-04-01 00:00 AM to 2014-04-01 5:00 AM = 5 hours

2014-04-01 11:00 PM to 2014-04-02 5:00 AM = 6 hours

2014-04-02 11:00 PM to 2014-04-02 11:59:59 PM = 0 hour 59 minutes 59 seconds

one second approximation is okay.

Upvotes: 0

Views: 1129

Answers (2)

user687474
user687474

Reputation:

You can use the CalendarPeriodCollector of the Time Period Library for .NET:

// ----------------------------------------------------------------------
public void NightHours()
{
    CalendarPeriodCollectorFilter filter = new CalendarPeriodCollectorFilter();
    filter.CollectingHours.Add( new HourRange( 0, 5 ) ); // working hours
    filter.CollectingHours.Add( new HourRange( 23, 24 ) ); // working hours

    CalendarTimeRange testPeriod =
       new CalendarTimeRange( new DateTime( 2014, 4, 1 ), 
       new DateTime( 2014, 4, 3 ) );
    Console.WriteLine( "Calendar period collector of period: " + testPeriod );

    CalendarPeriodCollector collector =
                    new CalendarPeriodCollector( filter, testPeriod );
    collector.CollectHours();
    Console.WriteLine( "Duration: " + new DateDiff( collector.Periods.TotalDuration ) );
} // NightHours

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98750

If these are strings, you need to parse them to DateTime with DateTime.ParseExact method and then get difference them with - operator. This gets you a TimeSpan. I see your strings have different formats. You need to parse them matched format one by one.

After that, you can use TimeSpan properties like;

string s = "2014-04-01 00:00 AM";
var date = DateTime.ParseExact(s,
                               "yyyy-MM-dd HH:mm tt",
                               CultureInfo.InvariantCulture);
string s1 = "2014-04-01 5:00 AM";
var date1 = DateTime.ParseExact(s1,
                                "yyyy-MM-dd H:mm tt",
                                CultureInfo.InvariantCulture);


TimeSpan ts = date1 - date;
Console.WriteLine(string.Format(@"{0} hours {1} minutes {2} seconds",
                                  ts.Hours, ts.Minutes, ts.Seconds));

Output will be;

5 hours 0 minutes 0 seconds

If they are already DateTime, just use - operator and use .Hours, .Minutes and .Seconds properties of TimeSpan structure.

There is a project called Calculating Business Hours which is calculate business hours between two DateTime. You can implement your own night shift hours based this project.

Upvotes: 2

Related Questions