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?
CodePudding user response:
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
CodePudding user response:
To format a date in date-fns as a UTC string, you can use the format function and pass in the 'UTC' option as the second argument. Here's an example:
import { format } from 'date-fns'
const date = new Date()
const utcString = format(date, 'UTC')
This will format the given date object as a UTC string in the format 'YYYY-MM-DDTHH:mm:ss.SSS[Z]', which is the same format as the toUTCString() method of the Date object in JavaScript.