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.
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:
new Date()
new Date(value)
new Date(dateString)
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
Great, the last form looks perfect. Off I went with this syntax:
const internationalWomensDay = new Date(2021, 3, 8)
Hmm, except the result was not as expected 🤔
internationalWomensDay.toString()
//'Thu Apr 08 2021 00:00:00 GMT+0100 (British Summer Time)'
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:
const internationalWomensDay = new Date(2021, 2, 8)
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?