JavaScript
Article

JavaScript Showing Wrong Year For Date

By Sam Deering

Quick post to let you JavaScript newbies out there that when declaring a date it might be showing the wrong year for the date. You may be thinking “javascript date returning later year, I was seeing 2012 instead of 2011, wtf?”. Consider the following examples:

So the date we want to see is Friday 15 July 2011.

var todaysDate = new Date();
console.log(todaysDate);
//output: Date {Fri Aug 12 2011 18:45:53 GMT+1000}

var expiryDate = new Date('15/07/2011');
console.log(expiryDate);
//output: Date {Wed Mar 07 2012 00:00:00 GMT+1000}

var expiryDate = new Date('07/15/2011');
console.log(expiryDate);
//output: Date {Fri Jul 15 2011 00:00:00 GMT+1000}

Can you work out whats going on? Well, JavaScript’s getMonth() function starts with 0 for January, 1 for February and so on… (you have to add one!) but this is the wrong year, day everything!

If we try parsing the date as single arguments this also doesn’t produce the correct results.

var expiryDate = new Date(2011, 15, 07);
console.log(expiryDate);
//output: Date {Sat Apr 07 2012 00:00:00 GMT+1000}

But, if we parse as a text date we get the correct results! :)

var expiryDate = new Date('July 15, 2011');
console.log(expiryDate);
//output: Date {Fri Jul 15 2011 00:00:00 GMT+1000}

Date’s can be a pain the A$$ so if your doing a lot of work with dates I would suggest to use a JavaScript DATE library to make managing dates in JavaScript a wizz!

This is an awesome date resource too (very comprehensive!).

No Reader comments

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.