简体   繁体   English

如何使用 date-fns 库格式化为 UTC 字符串?

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

In date-fns library I do this在 date-fns 库中,我这样做

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() .然而,这给了我本地化的价值,就像我做了new Date().toString()一样。 I am looking for the equivalent of new Date().toUTCString() .我正在寻找new Date().toUTCString()的等价物。 How can I format in date-fns to UTC string?如何将 date-fns 格式化为 UTC 字符串?

You can use formatInTimeZone from date-fns-tz to output the date in UTC:您可以使用formatInTimeZonedate-fns-tz到 output 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:这将 output 类似于:

 Local time: 08:23, December 6, 2022
 UTC: 16:23, December 6, 2022

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM