如何解决如何在 MomentJS 上获取 Date 对象但作为 UTC防止 `toDate()` 成为 `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
,我需要防止这同时仍然保留来自 Date object
的 .toDate()
。
我该怎么做?
解决方法
您需要使用 .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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。