Reese Schultz

Coding, gaming and rambling.

Why Your JavaScript Dates Are Wrong

Are you finding that output from Date.getDay, Date.getMonth or Date.getTimezoneOffset seems wrong? Learn how to fix that here.

Created on November 19, 2019.

There are three JavaScript Date functions with a tendency to throw people off. Those are:

  • Date.getDay
  • Date.getMonth
  • Date.getTimezoneOffset

Why? These functions are designed weird. Don't feel bad.

Date.getDay

Date.getDay does not return what you think it does. It returns the numbered day of the week based on the local time, not the day of the month, as you would reasonably expect. It's a zero-based index, so because Sunday is the beginning the week, it's represented by 0.

What you want instead is Date.getDate, which, don't worry, is a one-based index, meaning that the first day of the month is represented by 1.

Date.getMonth

While Date.getDate is a one-based index, you know, since it's a date, Date.getMonth is instead a zero-based index. That means November is represented by 10, instead of 11. Yes, wtf indeed.

Obviously the fix is to add one to the month, but this is nonetheless confusing and should be unnecessary in a rational world.

Date.getTimezoneOffset

Subtracting from Greenwich Mean Time (GMT), Date.getTimezoneOffset returns the local timezone offset in minutes, meaning that Coordinated Universal Time (UTC) minus five hours would return as 300 minutes from this particular function. Ugh.

You actually want to negate it and divide by 60 to perform the conversion to UTC hours. To get the local timezone offset with the conversion, just do this:

new Date().getTimezoneOffset() / -60

FYI, quoting MDN, "where the host system is configured for daylight saving, the offset will change depending on the date and time that the Date represents and that daylight saving applies."

Conclusions

All in all, JavaScript date handling can be unintuitive. Assuming you arrived here by searching one of the discussed functions, you probably aren't interested in a third-party library to streamline date handling. But if you are, I implore you to consider date-fns. You only use the functions you need, so this library is incredibly intuitive, lightweight and fast compared to alternatives such as Moment.js. Unfortunately, many people continue to use monolithic libraries that blow up their site footprint. Pick the right libraries—don't harm your SEO by picking the wrong ones.

© Reese Schultz

My code is released under the MIT license.