Why the JavaScript date is one day off?
by Maihan Nijat
JavaScript users are usually frustrated when they convert string to a date object. It’s important to understand the reasons behind the problem before jumping to the solution.
Let’s do some experiments to find the reasons:
We create a date object from the following string and print it in the console:
new Date('2019-09-20'; // Date Thu Sep 19 2019 20:00:00 GMT-0400 (Eastern Daylight Time)
CLEVER! You point out the one-day-off problem from the result. We expect the result Sep 20 2019 but got Sep 19 2019 instead but what else? The date object also sets hour 20:00:00 for us. From my point of view, the Date class reads my timezone (or getting offset Date().getTimezoneOffset()
)from the browser which is EST (Eastern Timezone) and converts it to GMT (Greenwich Mean Time) since we don’t specify the timezone for it. The EST is 5 hours behind, therefore, the date object returns Date Thu Sep 19 2019 20:00:00 GMT-0400 (Eastern Daylight Time) which makes sense. The date would be Sep 20 2019 if you convert the current date which is in GMT to EST.
The fun is not finished yet. Let’s create a date with a new Date(year, month, day) method and see what happens.
new Date(2019, 09, 20); // Date Sun Oct 20 2019 00:00:00 GMT-0400 (Eastern Daylight Time)
The above method ignores the TimezoneOffset and returns the date.
The Date class is full of surprises. The below also returns the date as GMT:new Date('2019/09/20') // Date Fri Sep 20 2019 00:00:00 GMT-0400 (Eastern Daylight Time)
Alright, I hope you understand the reasons behind the on-day-off problem from the above experiment. It’s all about TimezoneOffset which causes one day difference. Read more about TimeZoneOffset (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset)
We summarize it by providing quick solutions:
1- Use ‘/’ if you can like: new Date('2019/09/20')
2- Set time in the date like: new Date('2019-09-20 00:00:00');
3- Add the difference to your date with getTimezoneOffset:
let date = new Date("2019-09-20");
date = new Date(date.getTime() + date.getTimezoneOffset() * 60000)
Recommended Posts
What is JavaScript Promise – Explained with examples?
March 23, 2021
Privacy Policy for Keyboard
April 22, 2024
How to fix the MAC question mark folder issue?
August 3, 2021