TimeRange object for C#
In one of my recent .net projects (C#) I had the need to implement an object which represents a time range which is defined by a start time and an end time. In addition it should detect collision with other time ranges and check if given TimeSpans are within the time range itself. Last but not least it should support parsing time ranges from strings and format the range in a nice way. For this I've written a small class which could be useful for some of you out there.
Let's have a look how this thing needs to be used. There are three constructors for the usage so the creation of instances can be done in various ways. Additionally an instance can be obtained by using the Parse method. Some examples of creation...
-
TimeRange t = null;
-
//instances for a range of 10:00 - 12:00
-
-
//time range 00:00-24:00
-
-
//parsing time ranges from a string
-
t = TimeRange.Parse("10-12");
-
t = TimeRange.Parse("10:00-12:00");
If we have to ore more time ranges we can check if they colide. In other words if they overlap or clash. Everything the same :)
We can also check if a given TimeSpan is within the range or even another TimeRange.
That should be it. Have fun with it and dont hasitate to drop me any feedback about this stuff or even extensions.
Overview of C# TimeRange:
- Parsing a timerange out of a string (supports various formats)
- Parses also TimeSpan from a string (ParseTimeSpan method)
- Collision detection of two timeranges (inclusive and exclusive)
- Detection of a given TimeSpan is within the Range
- Equality check of time ranges
- Formatting in a user friendly way (ToString overridden)
The TimeRange for C# tested with .net framework 2.0 can be downloaded here...




December 6th, 2007 at 3:58 am
Thanks for the code, I found it usefull.
another example of use might be checking if the current time falls in a range:
static void Main(string[] args)
{
TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");
bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);
Console.ReadLine();
}
Cheers,
Stonie