Monday, September 26, 2011

Useful DateTime functions in JavaScript based on .NET DateTime

this post is exact copy of http://weblogs.asp.net/andrewrea/archive/2009/03/06/useful-datetime-functions-in-javascript-based-on-net-datetime.aspx



A question recently on StackOverflow.com triggered me to think that it would be nice if in JavaScript I could do this:

var d = new Date();
d.AddDays(1);


So exactly like what I can do in .NET. I know a lot of people try and achieve date solutions by concatenating strings and parsing as a date, but this is not an option for me as JavaScript’s native DateTime is very powerful and due to this, there is absolutely no need to be hashing together strings. So I will now paste the functionailty in C# that I based my methods on, dead simple, it is:

DateTime d = new DateTime();

public void Page_Load(object sender, EventArgs e)
{
DateTime days = d.AddDays(1);
DateTime hours = d.AddHours(1);
DateTime milliseconds = d.AddMilliseconds(1);
DateTime minutes = d.AddMinutes(1);
DateTime months = d.AddMonths(1);
DateTime seconds = d.AddSeconds(1);
}
So to exploit another JavaScript feature I will use prototype to extend the methods of the Date type inside javascript. C# now has extension methods which are quite similar in what they allow you to use them like. So the prototypes I want to create are as follows:

AddDays
AddHours
AddMilliseconds
AddMinutes
AddMonths
AddSeconds


Excellent, nice clean, precise code. So with this I can now do the following:




With the output of

Sat Mar 07 2009 08:41:09 GMT+0000 (GMT Standard Time)
Sat Mar 07 2009 09:41:09 GMT+0000 (GMT Standard Time)
Sat Mar 07 2009 09:41:09 GMT+0000 (GMT Standard Time)
Sat Mar 07 2009 09:42:09 GMT+0000 (GMT Standard Time)
Sat Mar 07 2009 09:43:09 GMT+0000 (GMT Standard Time)
Tue Apr 07 2009 09:43:09 GMT+0100 (GMT Daylight Time)
Tue Apr 07 2009 09:43:10 GMT+0100 (GMT Daylight Time)
Wed Apr 07 2010 09:43:10 GMT+0100 (GMT Daylight Time)

Obviously if you want to subtract values from a date you would provide negative values into the methods, i.e. DateTime.AddDays(-10);

Cheers for now,

Andy