【问题标题】:Get Epoch time value for different TimeZone获取不同 TimeZone 的 Epoch 时间值
【发布时间】:2020-05-21 13:56:25
【问题描述】:

我的本​​地时区是 IST,我尝试在 Date 对象中定义时区,例如

const usaRegionTime = new Date(inputDate.toString()).toLocaleString(
        'en-US',
        {
          timeZone: 'America/New_York',
        }
      );
      const estDate = new Date(usaRegionTime);
console.log(estDate.getTime());// Uses IST(local time Zone) instead of EST(Specifed time zone)

示例

我的 IST 时间是晚上 7:15,我使用带有 EST 时区的 Date 对象,我得到正确的 EST 作为上午 9:45,但是当我尝试 est.getTime() 时,UTC 计算为晚上 7:15 而不是 1:下午 45 点。在转换为 UTC(纪元)之前,它以上午 9:45 作为 IST(本地时区)。

问题是它以浏览器本地 timeZone(IST) 而不是 TimeZone(EST) 我作为参数提供给 Date 对象以获取 Epoch 值。有没有办法在获取 Epoch 值的同时用 Specified TimeZone 覆盖 Local time Zone

【问题讨论】:

标签: javascript angular date timezone


【解决方案1】:

有没有办法在获取 Epoch 值时用指定的时区覆盖本地时区。

没有。您可以为任何受支持的IANA representative location 生成时间戳,但不能为 Date 实例本身“设置时区”。

ECMAScript Date 对象只是一个时间值,它是从 1970 年 1 月 1 日 UTC 开始的毫秒偏移量。他们没有时区,只能在本地时区或 UTC 中工作,就是这样。解析特定时区的时间戳时,结果是 UTC 时间值。这是 Date 实例唯一记住的内容,因此无论您如何生成 Date,时间值始终是有效的 UTC。

普通的 getset 方法,如 getYeargetMintues 等,以及 toString 方法使用 UTC 时间值和主机设置来生成本地日期和时间值。 UTC getset 方法,如 getUTCYeargetUTCMintues 等以及 toISOString , toUTCString 等返回 UTC 值。因此,您可以在本地或 UTC 工作,而在其他时区或地点工作则需要您完成工作(这非常复杂,图书馆可能是更好的选择)。

您可以使用 toLocaleStringtimeZone 选项获取任何受支持的 IANA 代表位置的时间戳,但这只会影响生成的字符串,不会更改底层UTC 时间值。

您不能为 Date 对象设置时区或位置,因为它没有任何可以设置的属性,它只是一个 (UTC) 时间值,仅此而已。

此外,不需要内置解析器来解析 toLocaleString 的输出,主要是因为用户可以将输出配置为可能不包含任何日期或时间的大量不同格式值(例如,您可以获得时区或偏移量)。所以依赖解析这些值是有根本缺陷的。

【讨论】:

  • 谢谢 Rob 现在清楚了......正如你提到的,我怎样才能获得我设置为日期选项的时区的偏移量?
  • @Mithunabisheg——见this answer
【解决方案2】:
var date= new Date().valueOf(); //gives UTC timestamp in millisecond
const usaRegionTime = new Date(date).toLocaleString(
        'en-US',
        {
          timeZone: 'America/New_York',
        }
      );
  const estDate = new Date(usaRegionTime).toString();
console.log(estDate);

【讨论】:

  • 现在如果我们使用 estDate 的 getTime 方法,它将使用本地时区进行 Epoch 转换,但我想覆盖本地时区将进行 Epoch 转换
  • 谢谢,但这没有考虑夏令时,因此偏移量不能是恒定值,它会在一个周期内改变
  • 这仅在主机偏移设置与所需位置匹配时才有效。
猜你喜欢
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 2020-07-02
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多