I’m encountering an issue with the JavaScript Date object where it’s showing an incorrect date when I set it to midnight in UTC. Here’s my code:
function updateDates(startDate) {
var utcStartDate = startDate + 'T00:00:00Z';
var currentDate = new Date(utcStartDate);
console.log(startDate);
console.log(currentDate);
// Additional code to update dates in the UI
}
Here is console:
2024-02-26
list:4600 Sun Feb 25 2024 16:00:00 GMT-0800 (Pacific Standard Time)
I expect currentDate to represent the date specified by startDate at midnight in the UTC time zone. However, when I log currentDate, it’s showing a date one day earlier than expected, along with a time that doesn’t match midnight.
For example, if startDate is ‘2024-02-26’, I expect currentDate to be February 26, 2024, at midnight in UTC. Instead, I’m getting February 25, 2024, at 16:00:00 GMT-0800 (Pacific Standard Time).
I’ve tried setting the time zone offset to UTC (‘Z’), but it doesn’t seem to resolve the issue. It’s worth noting that this discrepancy occurs regardless of the local time zone settings of the environment.
I would appreciate any insights into why the Date object behaves this way and how I can ensure consistent results across different environments. Thank you!
2
Answers
The problem that your date is constructed properly as a UTC one, you can check that with
toUTCString()
. But unfortunately all Date’s methods works with local time likeDate#getHours()
,Date#toString()
.What you want is probably your local time at midnight that you INTERPRET later as an UTC date. That way all Date’s methods would return proper times you expect.
Just remove ‘Z’ in the end, that way your timezone isn’t involved in the parsing:
What I usually do:
All this is done automatically with API call hooks.
The date is always stored in terms of UTC but while displaying the browser converts it to the local timezone. You can use
.toISOString()
to get the time in UTC.More info – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
}