javascripttimestamptimezoneutcgmt

What exactly does the timeZone option do in Intl.DateTimeFormat()


I have difficulties to understand what the timeZone option in the Intl.DateTimeFormat() method exactly does. I could not find an in-depth resource on this, yet. Any explanation would be much appreciated.

Background: We need to display the timestamp of a backend server on the frontend and had some issues with the timezone offset. At the moment, I believe the solution to display the correct time depending on the local client time is the following:

Intl.DateTimeFormat('en-GB', {
          hour: 'numeric',
          minute: 'numeric',
          second: 'numeric',
          timeZone: 'GMT'
        }).format(timestamp)}

I do not fully understand, why I need to pass the option timeZone: 'GMT' for "Greenwich Mean Time' to get the correct time on the frontend.


Solution

  • The time zone is used to calculate the local time:

    const timeZones = [
        "GMT",
        "Europe/Madrid",
        "Asia/Tokyo"
    ];
    const timestamp = new Date();
    let displayDate;
    for (timeZone of timeZones) {
        displayDate = Intl.DateTimeFormat('en-GB', {
            hour: 'numeric',
            minute: 'numeric',
            second: 'numeric',
            timeZone: timeZone
        }).format(timestamp);
        console.log("%s @ %s", displayDate, timeZone);
    }

    If omitted altogether, it will default to current local time zone in the JavaScript runtime where the code runs:

    let displayDate = Intl.DateTimeFormat('en-GB', {
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
    }).format(new Date());
    console.log(displayDate);

    So the property can be used to make it explicit/static or to be able to use other time zones.