Over the course of my career, there have been several occasions where I needed a configurable time range where actions were allowed or disallowed. So about 6 months ago, I got round to creating a TimeRange type in my personal C# library.
The TimeRange can be constructed with either a null or empty string, or one in the form hh:mm-hh:mm to specify the time period.
Invalid string formats will cause an argument exception. Otherwise the public properties StartTime and EndTime are set. For example:
var timeRange = new TimeRange("22:00-04:00"); Assert.AreEqual("22:00-04:00", this.StartTime.ToString(@"hh\:mm") + "-" + this.EndTime.ToString(@"hh\:mm"))
The Contains method returns True if the given DateTime is within the time period.
var timeRange = new TimeRange("01:00-02:00"); Assert.IsTrue(timeRange.Contains(new DateTime(2013, 1, 1, 1, 30, 0)));
In addition, I’ve provided an explicit operator to convert from a string:
var timeRange = (TimeRange)"05:00-06:00";
and an implicit one, to convert back to a string:
var timeRange = new TimeRange("09:00-10:00"); string result = timeRange;
The class and unit test class are attached in zip form here. Feel free to use as you wish. Attributions would be appreciated.