I use getTimezoneOffset()
to get the offset in minutes for a given date object. Is is possible to use javascript to get timezone offset of a city or a country?
for example:
var offset = getCityOffset("Miami"); // returns -240
I use getTimezoneOffset()
to get the offset in minutes for a given date object. Is is possible to use javascript to get timezone offset of a city or a country?
for example:
var offset = getCityOffset("Miami"); // returns -240
No, there is nothing built-in to javascript which allows you to get the number of minutes to offset for specific time zones/cities.
getTimeZoneOffset
works for the current browser's settings
MomentJS Timezone extensions has some of this sort of functionality, which is of course reliant on the MomentJS library.
If you have access to Lat/Long values, then google provide a timezone API
I'm going to answer this question for Node.js using TypeScript (please remove the types if you want to use with plan JavaScript). For that, we will need 2 NPM packages.
Disclaimer: Timezones are COMPLEX. Not all timezones are 1 hour apart and some daylight saving time settings are weird with, for example, 15 minutes difference instead of the standard 60 minutes. This is a naive implementation that suited my use case. Use with discretion.
Code:
import * as cityTimeZones from "city-timezones";
import * as moment from "moment-timezone";
/**
* Returns the UTC offset for the given timezone
* @param timezone Example: America/New_York
*/
export function getNormalizedUtcOffset(timezone: string): number | null {
const momentTimezone = moment.tz(timezone);
if (!momentTimezone) {
return null;
}
let offset = momentTimezone.utcOffset();
if (momentTimezone.isDST()) {
// utcOffset will return the offset normalized by DST. If the location
// is in daylight saving time now, it will be adjusted for that. This is
// a NAIVE attempt to normalize that by going back 1 hour
offset -= 60;
}
return offset/60;
}
/**
* Returns the offset range for the given city or region
* @param location
*/
export function getUtcOffsetForLocation(location: string): number[] | null {
const timezones = cityTimeZones.findFromCityStateProvince(location);
if (timezones && timezones.length) {
// timezones will contain an array of all timezones for all cities inside
// the given location. For example, if location is a country, this will contain
// all timezones of all cities inside the country.
// YOU SHOULD CACHE THE RESULT OF THIS FUNCTION.
const offsetSet = new Set<number>();
for (let timezone of timezones) {
const offset = getNormalizedUtcOffset(timezone.timezone);
if (offset !== null) {
offsetSet.add(offset);
}
}
return [...offsetSet].sort((a, b) => a - b);
}
return null;
}
Unit tests (with Jest)
import { getUtcOffsetForLocation } from "../timezone";
describe("timezone", () => {
describe("getUtcOffsetForLocation", () => {
it("should work for Lisbon", () => {
expect(getUtcOffsetForLocation("Lisbon")).toEqual([0]);
});
it("should work for Berlin", () => {
expect(getUtcOffsetForLocation("Berlin")).toEqual([1]);
});
it("should work for Germany", () => {
expect(getUtcOffsetForLocation("Germany")).toEqual([1]);
});
it("should work for the United States", () => {
// when the region has multiple timezones,
expect(getUtcOffsetForLocation("United States")).toEqual( [-10, -9, -8, -7, -6, -5, -4]);
});
it("should return null for a non-existing region", () => {
// when the region has multiple timezones,
expect(getUtcOffsetForLocation("Blablabla")).toEqual( null);
});
});
});
you can use toLocaleTimeString() to find out the time of a particular city of a aprticular country , For example i want to determine the current time in 24 hour of India , so run this script
`let indianTime = new Date().toLocaleTimeString("en-US",
{timeZone:'Asia/Kolkata',timestyle:'full',hourCycle:'h24'})
console.log(indianTime)`
similarly for time of Dhaka/Bangladesh we can do the same
`let bangladeshTime = new Date().toLocaleTimeString("en-US",
{timeZone:'Asia/Dhaka',timestyle:'full',hourCycle:'h24'})
console.log(bangladeshTime)`
here i used a parameter en-Us to get the standard time format
TimeZoneOffset :
var d = new Date()
alert(d.getTimezoneOffset());
toLocaleTimeString() : This converts time to the local.
var d = new Date();
alert(d.toLocaleTimeString());
Using a library: refer, Auto Time zone detection & momentjs
function getTimeOffset(country = 'America/New_York', summerTime = false) {
let date = new Date(new Date().getFullYear(), summerTime ? 6 : 11, 1);
let wordTime = new Date(date.toISOString().substr(0, 19)).getTime();
let localTime = new Date(date.toLocaleString('en', { timeZone: country })).getTime();
return (wordTime - localTime) / 1000 / 60;
}
There is no default method. Although, there are few ways you can do it easily using the same getTimeZoneOffSet
method. One such tutorial is here. http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/
function calcTime(city, offset) {
// create Date object for current location
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
Note that this function requires you to pass the difference from GMT manually. You can use your code behind to get that parameter.