Get time of specific timezone
One way to do this is to use getLocaleString, like this:
Create a date object:
date = new Date(0)
If you are in Berlin, this should convert to this string:
Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
Get the hours in Athens:
date.toLocaleString('de-DE', {hour: '2-digit', hour12: false, timeZone: 'Europe/Athens' })
'02'
Get the hours in Shanghai:
date.toLocaleString('de-DE', {hour: '2-digit', hour12: false, timeZone: 'Asia/Shanghai' })
'08'
You could use Intl.DateTimeFormat
.
let options = {
timeZone: 'Europe/London',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
},
formatter = new Intl.DateTimeFormat([], options);
console.log(formatter.format(new Date()));
Alternatively, if you're formatting just once instead of bulk use Date.prototype.toLocaleDateString()
.
(new Date()).toLocaleString([], options)
Unfortunately browsers are not required to understand timezones other than UTC, so try
these blocks and figure out an alternative in case it fails, for example fetch the timezone offset from a server.
If you know the UTC offset then you can pass it and get the time using the following function:
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract 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 for city"+ city +" is "+ nd.toLocaleString();
}
alert(calcTime('Bombay', '+5.5'));
Taken from: Convert Local Time to Another