0

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?

omega
  • 40,311
  • 81
  • 251
  • 474
  • 1
    Why would you need to find the equivalent of something that's already built in? – phuzi Dec 06 '22 at 16:28
  • To get it outputted to a certain format i.e. "MMMM d, yyyy" – omega Dec 06 '22 at 19:03
  • For JavaScript Date formatting, take a look at this question over here https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript – phuzi Dec 06 '22 at 21:22
  • Thats a lot of manual parsing, a bit of stone age. If it was 1 function call with a formatter string, that would be good. – omega Dec 06 '22 at 22:40

1 Answers1

2

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
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40