Javascript’s new Date() 😱

A common pitfall with the constructor of Javascript’s Date object. It uses a base 0 for monthIndex parameter, but base 1 for others.

Photo by Charles Deluvio on Unsplash

So I needed to perform some date operations in Javascript, let’s take 8th March 2021 for this example. It was a sunny ☀️ day here in the UK. And it was International Women’s Day, which was a big deal in many places. Anyway’s let’s get back to Javascript.

I needed to convert the date to a Date object in Javascript so I could do things like calculating the day of the week, or how many days have passed since then.

Javascript has four constructors for the Date object:

Great, the last form looks perfect. Off I went with this syntax:

Hmm, except the result was not as expected 🤔

Why was it 8th April 2021 when I specifically passed in the value of 3 for March? It turned out that the parameter’s name monthIndex signifies something really important:

Integer value representing the month, beginning with 0 for January to 11 for December.

So the correct syntax for constructing the date 8th March 2021 is:

I am at loss to why it’s monthIndex and not month, and it’s base 0 and not base 1 😕. Especially so when year and day both use base 1! It took me a couple of hours of debugging to recognise this.

Have you fallen into this trap before?

Software developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store