Wednesday, April 27, 2011

FluentTime: a fluent interface in C# for working with dates and times

After working fairly late last night I was too wound up to go to sleep when I got home. Something possessed me to start creating a little C# library providing a fluent interface for working with DateTimes, DateTimeOffsets, and TimeSpans inspired by ActiveSupport's active_support/core_ext/numeric/time and related extensions.

After about 3.Hours(30.Minutes()) the straightforward part had come together. You can do stuff like this with it:

var toothBrushingTime = 10.Minutes().Before(bedTime);
var lightsOutForReal = 1.Hour(30.Minutes()).After(bedTime);
Assert.That(actual, Is.LessThan(50.Milliseconds().After(expected)));

These built in .NET types are pretty easy to work with and made the implementation very easy (except for the bit where I discovered that TimeSpan.FromMilliseconds takes a double but only has whole-millisecond precision).

This morning I put it up on Github. You can find FluentTime here.

The one more complex thing I'd still like to add is a variable-length variation on TimeSpan for handling units like months and years. I'm interested to see how clean I can keep things when my type will only take on a specific value based on the date-time value it's being added to or subtracted from. That ought to be a good opportunity for exploring operator overloading. (Unsurprisingly that hasn't come up in my day job just yet.)


Pablo Blamirez AKA PaulBlamire said...

This looks really nice, any plans to create a nuget package? I'm spoiled now.

jones said...

Hi, this is really interesting stuff - I had the exact same feeling! The native .net way of working with time felt wrong to me, so I created this dateapi! Have a look and tell me what you think!

jones said...

I really like this api! A couple of months ago I had the same problem and solved it using a fluent api just like FluentTime. While I started with some stuff like 5.Minutes().To(1.OClock()) I moved into stuff like 23.Febuary(2001). Have a look and tell me what you think :)

luke said...

yeah i like it! this is how it should be!

Boris Modylevsky said...

Great library. I like the fluent API, it is so readable and convenient. I use it in some side-project and would like to use it in another bigger one. I need it to be strong named. Is it possible?

John Hume said...

@Boris, sorry for the slow reply. Sorry to say, I don't even know what "strong named" means. I haven't touched .net in years at this point, so I'm not in a position to enhance the FluentTime library.

It is Apache-licensed, so you could fork it and do what you think needs doing.