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/, ' ').replace(/..+/, '')
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` 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 NodeJS 将 UTC 日期格式化为 `YYYY-MM-DD hh:mm:ss` 字符串?


基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 动态更新多个选择框 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01