omega
omega

Reputation: 43833

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

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?

Upvotes: 1

Views: 2295

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

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

Upvotes: 2

Related Questions