如何在 MomentJS 上获取 Date 对象但作为 UTC(防止 `toDate()` 成为 `locale`)?

How do I get a Date object on MomentJS but as UTC (prevent `toDate()` from being `locale`)?

首先,我确实需要一个 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,我需要为了防止这种情况,同时仍然保留来自 .toDate().

Date object

我该怎么做?

您需要使用.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>

我找到了 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>