[philiptellis] /bb|[^b]{2}/
Never stop Grokking


Tuesday, April 22, 2008

Javascript date functions

I keep forgetting what I can do with dates in javascript, so this post is just a list of built in date functions. I've also seen a lot of sites that do some terrible things with javascript dates including trying to parse it out of a string, or using getYear(). Don't do that.

I've also seen sites that contain arrays of calendar month names and days of the week. This is locale specific, so do it only if you're willing to make the array easily localised.

To create a new date object:
var d = new Date;

var d = new Date('2008/04/22');

var d = new Date('2008/04/22 01:03:31');

var d = new Date(1208758100000);
Note: don't type that into firefox/firebug while editing a post on blogger - they have a global variable called d which is used to save your post.

Also don't forget the new keyword. Without that you'll just create a string containing the current date.

After this line, d evaluates to a string representation of the date which isn't very useful for anything since it's almost always not what you want. You really want to get various parts of the date out. There's a whole bunch of functions to do that:
d.getYear();         // deprecated function to get year.  don't use this
d.getFullYear();     // get four digit year.  use this
d.getMonth();        // get the month 0 - 11
d.getDate();         // get the day of the month 1 - 31
d.getDay();          // get the day of the week 0-6 (Sunday is 0)
d.getHours();        // get the hour - 0-23.  Note the s in the function name
d.getMinutes();      // get the minutes of the hour - 0-59
d.getSeconds();      // get the seconds of the minute - 0-59
d.getMilliseconds(); // get milliseconds past the second - 0-999
d.getTime();         // get number of milliseconds since the epoch.  integer divide by 1000 to get unix timestamp
d.getTimezoneOffset(); // get offset from GMT in minutes - note capitalisation
All of these functions return the value for your current timezone. To get values in UTC, add UTC after the get in the method name. There are also equivalent set methods, but I've never needed to use them.

One useful method is parse() which takes in a string representation of a date and returns the number of milliseconds since the epoch for that. You can call this directly on the Date class.

A useful page for javascript date functions is quackit.com

I mentioned earlier that you should not use getYear();. This is so because this method is not quite Y2K compliant. It is sort of compliant, but browsers don't implement it in the same way. The standard says that it should return the number of years since 1900, which means 2000 would be 100 and 2008 would be 108. Netscape/Firefox does that correctly (possibly because they defined the standard back in the day), but IE decided to 'fix' it by returning 4 digit years for anything past 1999, which means that 1999 is 99 while 2000 is 2000. Your code gets unwieldy trying to manage it, so it's best to just use getFullYear().

I'd always thought about writing an equivalent to strftime for javascript, but never got down to it. In my mind, it would be something that uses a regex with a callback function, and I'd use the unique property of javascript that allows one to call an object's methods like keys in an associative array. Basically something like this:
var fmt = {'Y': 'getFullYear', 'm': 'getMonth', 'd': 'getDate'};
Date.prototype.strftime = function(str)
{
var d = this;
var ret = str.replace(/%([Ymd])/g, function(m0, m1)
{
return d[fmt[m1]]();
});
d=null;
return ret;
};
I'll have to build on that sometime.

Update: I've built an implementation of strftime in javascript. This implementation is also part of the YUI library.

3 comments :

Ray
January 31, 2009 11:22 PM

Just stumbled across this post while trying to figure out why IE was screwing with my dates. Using getFullYear() solved my problem. Thanks.

Blues
January 31, 2009 11:56 PM

glad it helped you. you could also use the full strftime implementation I made to do more complex date rendering.

hirentalsaniya
October 09, 2012 5:53 AM

test comment

Post a Comment

...===...