【问题标题】:how can I get a custom timezone datetime from utc timestamp with javascript(node.js)如何使用javascript(node.js)从utc时间戳获取自定义时区日期时间
【发布时间】:2018-01-05 00:15:56
【问题描述】:

我的后端服务器使用 python 存储一个 utc 时间戳并将其发送到前端。

from datetime import datetime
utcTs = datetime.utcnow().timestamp()

然后前端应用程序 (node.js) 获取 utcTs ,将其转换为语言环境时间(或自定义时区)

我的代码是这样的:

moment.unix(utcTs).add(8,'hour').format()

因为 utcTs 是 utc+0 时间戳,我如何将时刻对象初始化为 utc+0,这样我就可以轻松地将其转换为其他时区。

例如,我的语言环境是 utc+8。

moment.tz(utcTs,'Asia/Shanghai').format()

返回错误的时间。

有什么温和的方法吗?谢谢

【问题讨论】:

    标签: datetime timezone timestamp momentjs


    【解决方案1】:

    从 Python 的 timestamp() 方法返回的时间戳是从 Unix 纪元开始的基于 UTC 的秒数,因此您只需在 Moment 中执行相同的操作。

    // this is in seconds, but creates a moment in local mode
    moment.unix(utcTs).add(8,'hour').format()
    
    // you need to get it in UTC mode with the .utc().  Adding gives a moment 8 hours later.
    moment.unix(utcTs).utc().add(8,'hour').format()
    
    // this is how you get it in a fixed offset instead of adding
    moment.unix(utcTs).utcOffset('+08:00').format()
    

    由于并非所有时区都可以使用固定偏移量,因此以下是更好的方法。

    // this is incorrect, as the input would interpreted as milliseconds
    moment.tz(utcTs,'Asia/Shanghai').format()
    
    // this is the correct way for it interpreted in terms of seconds
    moment.unix(utcTs).tz('Asia/Shanghai').format()
    

    【讨论】:

    • 感谢马特,这个问题昨晚让我困惑了好几个小时。第三种方法我已经试过了。结果(线1)!=结果(线3)。请问可以试试吗?第 3 行的结果具有 +08:00 时区,比第 1 行的结果早 8 小时。我的语言环境 tz 是 +08:00。
    • console.log(moment.unix(utcTs).add(8,'hour').format()) console.log(moment.unix(utcTs).tz('Asia/Shanghai' ).format()) 和控制台打印如下: 2018-01-05T12:39:52+08:00 2018-01-05T04:39:52+08:00
    • 添加 8 小时与调整到 UTC+8 时区不同。添加 8 小时实际上是选择一个不同的时间点,即 8 小时后。 (另外,我很确定第一个会出现 +00:00,而不是 +08:00)
    • 啊,我看到了我的错误 - moment.unix(...)local 模式下返回片刻。我忘记了。对不起。相应地更新了我的答案。
    • 因为时刻是用当地时区计算的,所以第一行的结果是+08:00。我的本地时区是 +08:00。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2018-01-17
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2014-11-21
    相关资源
    最近更新 更多