[英]How do I get a Date object on MomentJS but as UTC (prevent `toDate()` from being `locale`)?
First of all, I really need a Date object
because I'm using ReactDatePicker
and the selected
prop requires it.首先,我真的需要一个Date object
因为我使用的是ReactDatePicker
并且selected
道具需要它。 And I also really have to use momentjs
.而且我也真的必须使用momentjs
。
The bit of code I need to work with is this:我需要使用的代码是这样的:
// 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()
As you can see, no matter the amount of times that I convert my moment()
into UTC
, toDate()
always converts it back to locale time
and I need to prevent this while still keeping a Date object
that comes from .toDate()
.如您所见,无论我将moment()
转换为UTC
, toDate()
始终会将其转换回locale time
,我需要防止这种情况发生,同时仍保留来自.toDate()
的Date object
.
How can I do this?我怎样才能做到这一点?
You need to use the .valueOf()
method.您需要使用.valueOf()
方法。
Following on from your example继您的示例之后
// 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>
I found this thread .我找到了这个线程。
Where someone found success by placing .format()
out of the brackets.有人通过将.format()
放在括号之外而获得成功。 For me it yields the same result, but it might be worth trying if you are still having problems.对我来说,它产生相同的结果,但如果您仍然遇到问题,可能值得尝试。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.