Skip to main content

JavaScript Showing Wrong Year For Date

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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();
//output: Date {Fri Aug 12 2011 18:45:53 GMT+1000}

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

var expiryDate = new Date('07/15/2011');
//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);
//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');
//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!).

Related Articles

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn the basics of programming with the web's most popular language - JavaScript

A practical guide to leading radical innovation and growth.

Integromat Tower Ad