Javascript Date is One Day Off

ben himself's picture

In JavaScript, dates are based on the UTC time, the starting timezone which all others are based on. You may have a date in JavaScript that should be one particular date but for some reason changes itself to the previous day. The way to fix it is to add the timezone offset to the date. Here's an example:

jsfiddle example: https://jsfiddle.net/xhzce36p/1/

To be more specific, what is happening is the date defaults to a time of midnight, so 5/1/2019 is actually 5/1/2019 12:00:00 AM

If you subtract a few hours (four, in my case) because you're in a timezone that is not the UTC+0 timezone, the date becomes 4/30/2019 08:00:00 PM. If you're only displaying the date and not the time, you'll see 4/30/2019. It probably won't be obvious when you see it. All you see is that your date is off by a day. Well, now you know why.