Search code examples
javascriptdatetimetime-format

Get absolute current date in Javascript


I want to get the current date in the UTC - 7 timezone.

Every method I tried starts with a local date, and I want that any user from any timezone gets the same date.


Solution

  • I would suggest using a library such as Moment Timezone for this purpose, this will handle Daylight Saving Time changes properly as well.

    You can also use Date.toLocaleString() to get the formatted time in a given timezone

    function getTimeInTimezone(timezone) {
        return moment.tz(timezone);
    }
    
    /* Using moment timezone */
    let m = getTimeInTimezone("Etc/GMT+7");
    console.log("Time in UTC-7 (moment):", m.format("YYYY-MM-DD HH:mm:ss"));
    
    let d = new Date();
    console.log("Time in UTC-7 (toLocaleString):",  d.toLocaleString('en-GB', { timeZone: "Etc/GMT+7" }));
     
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data-10-year-range.js"></script>