如何使用NodeJS将UTC日期格式化为“YYYY-MM-DD hh:mm:ss”字符串? [英] How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?
本文介绍了如何使用NodeJS将UTC日期格式化为“YYYY-MM-DD hh:mm:ss”字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用NodeJS,我想将 Date
格式化为以下字符串格式:
Using NodeJS, I want to format a Date
into the following string format:
var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");
我该怎么做?
推荐答案
如果您正在使用Node.js,那么您肯定要使用EcmaScript 5,因此Date具有 toISOString
方法。您要求稍微修改ISO8601:
If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString
method. You're asking for a slight modification of ISO8601:
new Date().toISOString()
> '2012-11-04T14:51:06.157Z'
所以只需剪掉一些东西,你设置好了:
So just cut a few things out, and you're set:
new Date().toISOString().
replace(/T/, ' '). // replace T with a space
replace(/\..+/, '') // delete the dot and everything after
> '2012-11-04 14:55:45'
或者,在一行中: new Date()。toISOString()。replace(/ T /,'')。renplace(/ \ .. + /,'')
ISO8601必然是UTC(也由第一个结果的尾随Z表示),所以你默认得到UTC(总是好事)。
ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).
这篇关于如何使用NodeJS将UTC日期格式化为“YYYY-MM-DD hh:mm:ss”字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文