Search code examples
javascriptdatedatetimeutcdate-conversion

JavaScript Date object showing incorrect date when set to midnight in UTC


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!


Solution

  • 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 like Date#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:

    function updateDates(startDate) {
        var utcStartDate = startDate + 'T00:00:00';
        var currentDate = new Date(utcStartDate)
    
        console.log(startDate);
        console.log(currentDate.toString());
    
        // Additional code to update dates in the UI
    }
    
    updateDates('2024-04-26');

    What I usually do:

    1. When data comes from a backend - convert all UTC date strings to local Dates
    2. When I post data to a backend - convert all local Dates to UTC strings.

    All this is done automatically with API call hooks.