JavaScript – Date Format

I’ve had a few questions on this lately and since JavaScript date formats are rather easy, here’s some code:

var now = new Date();

alert(now.getMonth()+"/"+now.getDate() + "/" + now.getYear());
// returns 4/01/12

// format names
var now = new Date();
alert(now); // 8:00:00 AM EST

Other named formats include:

You can also parse a string to a date. To parse a string and convert to a date, just use the parse() method. For example:

var dd = Date.parse("04/01/2012");
alert(dd); // returns 1333252800000

But JavaScript does not have a DateFormat object you might be use to from other languages. I’ve found one that looks rather good here.

With this library you can call a format method on the date object so that:

var dd = new Date();
alert(dd); // returns "4/1/12"

If you have any questions about this, comment or send me a note.