简体   繁体   English

Javascript中特定日期的时区名称的时区偏移量

[英]Timezone offset by timezone name for a specific date in Javascript

How can I find timezone offset in hours or minutes using timezone name for a specific date.如何使用特定日期的时区名称以小时或分钟为单位查找时区偏移量。

Example use would be :示例用途是:

var offset = findOffset("America/New_York", new Date(2019,08,07))
// offset is -4

I am hoping to find a solution using native JS, but if it does not exist I am also ok with using some libraries.我希望找到使用本机 JS 的解决方案,但如果它不存在,我也可以使用一些库。

I will recommend Moment Timezone which is a JS library and it is quite popular (3,660,521 weeks NPM downloads).我会推荐Moment Timezone ,它是一个 JS 库,它非常流行(3,660,521 周 NPM 下载量)。 Moment and Moment Timezone are sibling libraries (Same developer). Moment 和 Moment Timezone 是兄弟库(同一开发人员)。

The moment timezone library gives you offset in the output like shown below: 时刻时区库为您提供输出中的偏移量,如下所示:

moment.tz("2013-12-01", "America/Los_Angeles").format(); // 2013-12-01T00:00:00-08:00

moment.tz("2013-06-01", "America/Los_Angeles").format(); // 2013-06-01T00:00:00-07:00

So here is the answer I found所以这是我找到的答案

const findTimeZoneOffset = (tz,date) => {
  let utcDate = new Date(date.toLocaleString('en-US', { timeZone: "UTC" }));
  let tzDate = new Date(date.toLocaleString('en-US', { timeZone: tz }));
  let diff = ( tzDate.getTime() - utcDate.getTime() ) / 1000 / 60 / 60;
  return diff;
};

and as expected正如预期的那样

findTimeZoneOffset("America/New_York", new Date(2019,08,07))
// returns -4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM