Aug 04, 2008 / .net ~ rails ~ c#
Funky C# Extension Methods for Date Time (Inspired by Rails)

Ruby on Rails introduced me to some great helpers for for date and time. Rails lets you write code like this:

#returns the time in 10 minutes from now
10.minutes.from_now 

#use to compare dates in a DSL style syntax
if order.created_at < 1.day.ago then .... 

The beauty of this is that you can express dates and times in a nice, human readable way.

I was hoping to re-create this fluent interface in .NET, now that we have C# extension methods. I managed to get these working in about 10 minutes flat.

22.Hours().Ago            
5.Days().Ago 
3.Days().FromNow
12.Months().FromNow

Unfortunately we don't have Extension Properties yet, so I have to have those parenthesis as shown above.

As many have pointed out, this would look much nicer:

22.Hours.Ago
2.Days.FromNow

Moving on, I've just started another experiment which should be doable...

24.Minutes().After.Midday   
2.Minutes().To.Midnight
10.Seconds().Before.NewYear

I'm too lazy/tired to finish this tonight, but might have a stab later this week and I'll post the source code up then too.

Before I invest any real time, am I duplicating someone elses work here? Surely someone has done this already?


You may also like...