Search code examples
javascriptmomentjsreact-datepicker

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 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().

How can I do this?


Solution

  • 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>