Search code examples
javascriptdate-fns

How to make date-fns's format function return times in UTC (not local time)?


Is there a way to get the following code to output hours in UTC time?

format(date, 'MM/dd/yy hh:mm a') // outputs 01-17-2020 03:25 PM

How would I make output 01-17-2020 11:25 PM?


Solution

  • Welcome to Stack Overflow.

    There is a function

    date.toUTCString(); // Returns "Sat, 02 Mar 2019 13:00:00 GMT"
    

    Or there are individual functions like . getUTCMonth()

    So you could do this with

    console.log(`${date.getUTCMonth()}/${date.getUTCDay()}/${date.getUTCYear()} ${date.getUTCHour()}:${date.getUTCMinute()}`)
    

    More information here: https://dev.to/mcapodici/javascript-dates-2dbj

    Or, better still, you could use momentjs, which has a UTC mode, like this:

    moment().format();     // 2013-02-04T10:35:24-08:00
    moment.utc().format(); // 2013-02-04T18:35:24+00:00