Skip to content Skip to sidebar Skip to footer

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 objectconst date = moment(moment.utc().valueOf())

// This will output something like 2021-07-20T16:14:39.636Zconst dateObj = date.toDate()

// this logs a Moment objectconst date = moment(moment.utc().valueOf())

// This will output something like 2021-07-20T16:14:39.636Zconst dateObj = date.toDate()

console.log("UTC time: ", dateObj)
<scripttype="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 timeconsole.log("dateObj is an " + typeof dateObj)
console.log("dateObj is " + (dateObj._isAMomentObject ? "a moment object" : "not a moment object"))
<scripttype="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`)?"