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

san*_*han 2 javascript

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

例如:

var offset = getCityOffset("Miami"); // returns -240
Run Code Online (Sandbox Code Playgroud)

And*_*ena 8

我将使用 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;
}
Run Code Online (Sandbox Code Playgroud)

单元测试(使用 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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)


Jam*_*iec 7

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

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

MomentJS Timezone扩展具有一些此类功能,当然这些功能依赖于MomentJS库.

如果您可以访问Lat/Long值,那么Google会提供时区API