<< back to blog

Funky C# Extension Methods for Date Time (Inspired by Rails)

.net ~ rails ~ c#

04 Aug, 2008

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...
.NET Gem Fun
Running FubuMVC on Mono (OSX)
Really Easy Way To Partition an ASP.NET MVC With An Admin Area
Automating .NET development (and NHibernate) with IronRuby + Rake
Get a Rails-Stylee Interactive Shell For Your NHibernate Backed Domain Model
In Memory SQLite Testing with NHibernate
NHibernate Trick
OSX MonoDevelop MVC?
NHibernate: Calling Update Unnecessarily
.NET Config for Multiple Developers

kick it on DotNetKicks.com
blog comments powered by Disqus