Thursday, June 13, 2013

Just Time for .NET

I need to represent just time in .NET, no date. My scenario is that I have a scheduler and I want to run a job 4 times a day at specific hour: 4:00, 10:00, 16:00, 22:00. There is no default data type in .NET to represent this kind of information. DateTime requests from me setting a Date (which is irrelevant in my scenario), and also the simplest DateTime constructor that uses hour also requests from me setting minutes and seconds, which again are irrelevant for me. The simplest constructor using DateTime looks like:
new DateTime(year:1, month:1, day:1, hour:4, minute:0, second:0);

If I try to parse a date from a string and I pass just time a date is set by default to "01/01/01" and I find it silly.
I can use TimeSpan, but this data type was design to keep a span of a time, not a point of a time, and it is really misleading.
The approach I took is to install NodaTime and there is a nuget package. Inside NodaTime there is a class called Period that is meant to represent exactly what I need a period in time. Constructor that I used is listed below.
Period.FromHours(4);

No comments: