Is there a way to define a time interval in C#?

I want to define a time interval and check if System.DateTime.Now is within that interval. Is there a way to do that? It seems you can only define a specific time using TimeSpan.

I think I can define two TimeSpan for the start and end of the interval but I think it saves a lot of time if I can just define the interval and use it to compare directly.

Jon Skeet
people
quotationmark

Firstly, I wouldn't use DateTime.Now - you should almost certainly be using DateTime.UtcNow, assuming you really want it to be an interval of elapsed time rather than local time. An interval of local time could lead to some really weird behaviour, e.g. if you set it to 01:45 to 02:15 local time, on the day when the clocks go back at 2am...

But beyond that, you could define it to be between two DateTime or DateTimeOffset values - I wouldn't use TimeSpan for this.

Alternatively, you could use my Noda Time project which already defines an Interval type... (and is, IMO, a better date/time API in general... it would be relatively hard to accidentally make the mistake about using local values for the interval using Noda Time, for example)

people

See more on this question at Stackoverflow