format datetime specific timezone

976 Views Asked by At

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?

2

There are 2 best solutions below

4
R. McManaman On BEST ANSWER

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!

2
Dragonman86 On

The javascript function new date() generates a date/time stamp based off the machine time at the moment that the function was called. So if the function is called by a machine that is in Alaska, it will generate a date/time stamp based on the current time in Alaska at that exact moment.

w3school.com has great references to most coding related items. You can find the answer to your question here.