Sunday, July 25, 2010

Fun with Javascript Dates III

Level:Moderate

Javascript Date objects can be created with the following parameters:
new Date(year, month, date, hours, minutes, seconds, milliseconds)
If you only specify the first two parameters, all others are assumed to be zero.
This date instantiator has a very interesting feature. The parameters for month, date(i.e. monthday), hours etc do not have the standard upper and lower bound. They can be any integer. For example monthday can be negative or greater than 31.

var d = new Date(2010,0,1) // will yield 1st Jan 2010
var d = new Date(2010,0,-2) // 29 Dec 29 2009 (back 3 days)
var d = new Date(2010,0,-2, 100) //1st Jan 2010, 4am (minus 3 days plus 100 hours)

This was a very cool design decision, because now it becomes very easy to perform date addition.

1. Add/Subtract days and months etc to a date

var d = new Date(); //today's date
var d2=new Date(d.getFullYear()+3,d.getMonth()+4,d.getDate()+5)
//d2 is set to 3 years, 4 months and 5 days in the future

Better still, we can extend the Date Object’s behavior and add this functionality.

Date.prototype.addDays = function(days) {
return new Date(this.getFullYear(),this.getMonth(),this.getDate()+(+days))
}
//See my ParseInt blog if you think the (+days) is odd looking
//Usage:
//var now = new Date();
//var Yesterday = now.addDays(-1);
//alert(Yesterday);

I’ll leave it up to you to implement addMonths() and addYears(), Hours, Minutes, Seconds.

2. Day of the Year: (Julian Day)

Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}

3. Week of Year

Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

4. Fiscal Year if your new year starts on October 1st of the previous year.
We can use the addDays() prototype function we just created!

Date.prototype.getFiscalYear = function() {
return this.addDays(92).getFullYear();
}

Datejs library on googlecode, has amazing functionality added on to the Date object. Many other major frameworks have similar libraries.

No comments: