This page looks best with JavaScript enabled

Javascript date feature that I could have lived without

 ·   ·  ☕ 2 min read

Be aware of hidden Javascript features that can break your code before you say “ugh..”.

Consider the below code that prints today’s date -

1
2
3
const dt = new Date();
console.log("dt: ", dt);
// 2019-03-31T13:56:42.552Z

All looks good? Let us now create a target date for my payment - it is 1.5 months from now.

1
2
3
4
5
const dt1 = new Date(2019, 05, 15);
console.log("dt1: ", dt1);
// 2019-06-14T18:30:00.000Z
// well - diff. time-zone causes one day prior
//  .. but that's ok

Don’t mind the day gap, we are just living in the wrong time zone. We are happy with 15-Jun allright.

Wait, there is another way to set dates. We will try that for the heck of it.

1
2
3
4
5
6
7
const dt2 = new Date();
dt2.setFullYear(2019);
dt2.setMonth(5);
dt2.setDate(15);
console.log("dt2: ", dt2);
// 2019-07-15T13:56:42.594Z
// wait what?

We have just added a month to my target payment date. There is a God?

Not so great news if you are on the business side of things. And, the not-so-funny thing - I did not notice this until it “failed” in production.

Why did this happen? It turns out there is a legit reason.

When you input a dt2.setMonth(5) -

  1. Month will be set to ‘June’
  2. Date will be defaulted to today’s date (='31’) since there was no date provided (as yet)
  3. Since there is no ‘31-Jun’, Javascript helpfully pushes date by one day -> ‘1-Jul’

Next up: we provide the actual date (‘15’), Javascript sets date to ‘15’.

End result - 15-Jul-2019.

Hmm.. it is time for a break. Where can I find the nearest ☢ 💥?

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things