How to format as UTC string with date-fns library?

How to format as UTC string with date-fns library?

Problem Description:

In date-fns library I do this

var from = new Date();
format(from, "MMMM d, yyyy");

However this gives me the localized value similarly as to if I did new Date().toString(). I am looking for the equivalent of new Date().toUTCString(). How can I format in date-fns to UTC string?

Solution – 1

You can use formatInTimeZone from date-fns-tz to output the date in UTC:

let { format  } = require('date-fns');
let { formatInTimeZone } = require('date-fns-tz');

var from = new Date();

console.log('Local time:', format(from, 'HH:mm, MMMM d, yyyy'))
console.log('UTC:', formatInTimeZone(from, 'UTC',  'HH:mm, MMMM d, yyyy'))

This will output something like:

 Local time: 08:23, December 6, 2022
 UTC: 16:23, December 6, 2022
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.