如何在javascript中获取城市或国家的时区

时间:2016-05-03 10:37:19

标签: javascript

我使用getTimezoneOffset()来获取给定日期对象的分钟偏移量。是否可以使用javascript获取城市或国家/地区的时区偏移量?

例如:

var offset = getCityOffset("Miami"); // returns -240

4 个答案:

答案 0 :(得分:6)

不,javascript中没有任何内置功能可让您获得特定时区/城市的偏移分钟数。

getTimeZoneOffset适用于当前浏览器的设置

MomentJS Timezone extensions有一些这样的功能,当然这依赖于MomentJS库。

如果您可以访问Lat / Long值,则Google提供a timezone API

答案 1 :(得分:1)

TimeZoneOffset:



var d = new Date()
alert(d.getTimezoneOffset());




toLocaleTimeString():这会将时间转换为本地。



var d = new Date();
alert(d.toLocaleTimeString());




使用图书馆:referAuto Time zone detection& momentjs

答案 2 :(得分:1)

我将使用TypeScript回答有关Node.js的问题(如果要与计划JavaScript一起使用,请删除类型)。为此,我们将需要2个NPM软件包。

免责声明:时区是复杂的。并非所有时区都相隔1小时,并且某些夏时制设置很奇怪,例如相差15分钟而不是标准的60分钟。这是一个天真的实现,适合我的用例。谨慎使用

代码:

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;
}

单元测试(带有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);
    });
  });
});

答案 3 :(得分:-4)

没有默认方法。虽然,使用相同的getTimeZoneOffSet方法可以轻松地完成此操作。一个这样的教程就在这里。 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();

}

请注意,此功能要求您手动传递GMT的差异。您可以使用后面的代码来获取该参数。