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. And I also really have to use momentjs. The bit of code I need to wor
Solution 1:
You need to use the .valueOf()
method.
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>
Solution 2:
I found this thread.
Where someone found success by placing .format()
out of the brackets. 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>
Post a Comment for "How Do I Get A Date Object On MomentJS But As UTC (prevent `toDate()` From Being `locale`)?"