Search code examples
javascriptdatetimezoneutc

Convert UTC date received from server to local timzone date in Javascript


Working with Javascript, I want to convert the UTC date received from the server to the local timezone date object in the client's browser.

Which function/code do I have to use in Javascript? For example, converting this UTC date: '2021-01-20T17:40:35'.


Solution

  • The format '2021-01-20T17:40:35' is supported by ECMA-262, but without a timezone it's parsed as local. If you want it parsed as UTC just add "Z" to set the offset to 0, so:

    new Date('2021-01-20T17:40:35' + 'Z')
    

    parses the string as UTC. Then the local date and time is returned by the various get* methods, or just toString.

    However, if you want a truely robust function, parse it manually, e.g.

    // Get the parts
    let [Y, M, D, H, m, s] = '2021-01-20T17:40:35'.split(/\D/);
    // Treat as UTC
    let date = new Date(Date.UTC(Y, M-1, D, H, m, s));
    

    There are many questions on formatting dates. Any toString method that doesn't include the characters "UTC" or "ISO" will return local values based on the host system's regional settings for timezone and DST.

    E.g.

    let [Y, M, D, H, m, s] = '2021-01-20T17:40:35'.split(/\D/);
    let date = new Date(Date.UTC(Y, M-1, D, H, m, s));
    
    // Formatted as specified in ECMA-262
    console.log(date.toString());
    // So-called "locale aware" string, based on language
    console.log(date.toLocaleString());
    // In another timezone for Antarctica/McMurdo
    console.log(date.toLocaleString('default', {timeZone: 'Antarctica/McMurdo', timeZoneName: 'short'}));