Search code examples
javascriptdate-formattingjavascript-globalize

format datetime specific timezone


I am using globalize to format datetime per locale.

var Globalize = require('globalize');
var formatter = Globalize('en-US').dateFormatter();
formatter(new Date());

It works great but I was wondering if I can format date for specific timezone. This way, it always formats date in the local machine timezone. For example, let's say my machine timezone is PST. Can I use globalize to format date in EST?


Solution

  • Stolen from here

    This solution works by using the getTimeOffset() (which returns the time difference between UTC time and local time, in minutes) function to find the UTC time offset of a given location and changing it to milliseconds, then performing calculations from UTC to return a time for a different time zone.

    /** 
     * function to calculate local time
     * in a different city
     * given the city's UTC offset
     */
    function calcTime(city, offset) {
    
    // create Date object for current location
    var d = new Date();
    
    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    
    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));
    
    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
    }
    

    This solution will work, but it's simpler to express timezone in minutes and adjust the UTC minutes.

    Please let me know if this works for you!