Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

javascript - 如何使用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?)

Using NodeJS, I want to format a Date into the following string format:(使用NodeJS,我想将Date格式化为以下字符串格式:)

var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");

How do I do that?(我怎么做?)

  ask by Tampa translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method.(如果你正在使用Node.js,你肯定有EcmaScript 5,所以Date有一个toISOString方法。)

You're asking for a slight modification of ISO8601:(您要求稍微修改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'

Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')(或者,在一行中: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''))

ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).(ISO8601必须是UTC(也由第一个结果的尾随Z表示),因此默认情况下会获得UTC(总是一件好事)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...