【问题标题】:How do I get a Date object on MomentJS but as UTC (prevent `toDate()` from being `locale`)?如何在 MomentJS 上获取 Date 对象,但作为 UTC(防止 `toDate()` 成为 `locale`)?
【发布时间】:2021-07-20 16:11:22
【问题描述】:

首先,我真的需要Date object,因为我使用的是ReactDatePicker,而selected 属性需要它。而且我还真的必须使用momentjs

我需要处理的代码是这样的:

// this logs a Moment object
const date = moment(moment.utc().format())

// this logs something like
// Tue Jul 20 2021 17:08:28 GMT+0100 (Western European Summer Time)
const dateObj = date.toDate()

如您所见,无论我将moment() 转换为UTC 多少次,toDate() 总是将其转换回locale time,我需要在保持Date object 的同时防止这种情况发生来自.toDate()

我该怎么做?

【问题讨论】:

    标签: javascript momentjs react-datepicker


    【解决方案1】:

    您需要使用.valueOf() 方法。

    从你的例子开始

    // this logs a Moment object
    const date = moment(moment.utc().valueOf())
    
    // This will output something like 2021-07-20T16:14:39.636Z
    const dateObj = date.toDate()
    

    // this logs a Moment object
    const date = moment(moment.utc().valueOf())
    
    // This will output something like 2021-07-20T16:14:39.636Z
    const dateObj = date.toDate()
    
    console.log("UTC time: ", dateObj)
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

    【讨论】:

    • 我可能错了,但这似乎不起作用。做你的回答我没有得到UTC,而是我仍然从toDate()得到locale time。甚至moment(moment.utc().valueOf()) 也已作为locale time 提供
    • 时间绝对是 UTC,取决于您居住的地方 UTC 时间(协调世界时)可能与您的本地时间相同。 @ItzaMi
    • 一个interesting website,根据 UTC 偏移量将国家/地区分组在一起。
    • 这很奇怪。我在 GMT+1 上,如果记录 moment(moment.utc().valueOf()) 我得到了我当前的 locale 时间,当然,记录 moment(moment.utc().valueOf()).toDate() 也记录了我的 locale time。我可以看到您的示例正在运行,但我不明白为什么它会为我这样做。我在这个 React 项目中使用 "moment": "2.29.1"
    • moment(moment.utc().valueOf()).toDate() 的输出对您来说是什么样的。您使用的是最新版本的 moment.js。
    【解决方案2】:

    我找到了this thread

    有人通过将.format() 置于括号外而获得成功。对我来说,它会产生相同的结果,但如果您仍然遇到问题,可能值得一试。

    const date = moment(moment.utc())
    
    const dateObj = moment(date.format()) // Equivalent to moment(moment(moment.utc()).format())
    
    console.log("UTC time: ", dateObj) // Should output UTC time
    console.log("dateObj is an " + typeof dateObj)
    console.log("dateObj is " + (dateObj._isAMomentObject ? "a moment object" : "not a moment object"))
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

    【讨论】:

    • 这不起作用。我的道具期待Dateformat() 让我得到string
    • @ItzaMi 我的错,我已经修复了 sn-p 以返回一个时刻对象。
    猜你喜欢
    • 2019-11-12
    • 2021-09-29
    • 2021-07-02
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多