我想用 NodeJS 将一个 Date
格式化为以下字符串格式:
var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");
如何做到这一点?
我想用 NodeJS 将一个 Date
格式化为以下字符串格式:
var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");
如何做到这一点?
如果你正在使用Node.js,那么你肯定有EcmaScript 5,并且Date对象有一个toISOString
方法。你需要对ISO8601进行轻微修改:
new Date().toISOString()
> '2012-11-04T14:51:06.157Z'
只需要删减一些内容,你就可以开始了:
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时间(这总是件好事)。
new Date().toISOString().replace('T', ' ').substr(0, 19)
。 - klh(new Date()).toISOString().slice(0,16).replace('T',' ')
,去掉了正则表达式。这样可以得到没有秒数的答案。 - Julian Knight更新时间2021-10-06: 添加Day.js并删除@ashleedawg的无用编辑
更新时间2021-04-07: 添加了@Tampa提供的Luxon。
更新时间2021-02-28: 应该注意Moment.js不再被积极开发。它不会很快消失,因为它嵌入了很多其他东西。该网站提供了一些替代方案和解释。
更新时间2017-03-29: 添加了date-fns,并对Moment和Datejs做了一些备注
更新时间2016-09-14: 添加了SugarJS,它似乎有一些出色的日期/时间函数。
好吧,既然没有人真正提供实际的答案,那么这就是我的答案。
在标准化处理日期和时间时,使用库是最好的选择。在日期/时间计算中有很多边缘情况,因此将开发交给库是很有用的。
以下是主要与Node兼容的时间格式化库列表:
此外,还有非 Node 库:
有一个用于转换的库:
npm install dateformat
然后写下您的要求:
var dateFormat = require('dateformat');
然后绑定该值:
var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");
请查看dateformat
我并不反对使用库。但在这种情况下,一个通用的库似乎过度了,除非应用程序的其他部分需要频繁处理日期。
编写此类小型实用程序函数对于初学者和有经验的程序员来说都是一种有用的练习,对于我们中的新手来说也可以是一次学习经历。
function dateFormat (date, fstr, utc) {
utc = utc ? 'getUTC' : 'get';
return fstr.replace (/%[YmdHMS]/g, function (m) {
switch (m) {
case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
case '%m': m = 1 + date[utc + 'Month'] (); break;
case '%d': m = date[utc + 'Date'] (); break;
case '%H': m = date[utc + 'Hours'] (); break;
case '%M': m = date[utc + 'Minutes'] (); break;
case '%S': m = date[utc + 'Seconds'] (); break;
default: return m.slice (1); // unknown code, remove %
}
// add leading zero if required
return ('0' + m).slice (-2);
});
}
/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns
"2012-05-18 05:37:21" */
请检查下面的代码和链接:Date对象,Intl.DateTimeFormat
// var ts_hms = new Date(UTC);
// ts_hms.format("%Y-%m-%d %H:%M:%S")
// exact format
console.log(new Date().toISOString().replace('T', ' ').substring(0, 19))
// other formats
console.log(new Date().toUTCString())
console.log(new Date().toLocaleString('en-US'))
console.log(new Date().toString())
// log format
const parts = new Date().toString().split(' ')
console.log([parts[1], parts[2], parts[4]].join(' '))
// intl
console.log(new Intl.DateTimeFormat('en-US', {dateStyle: 'long', timeStyle: 'long'}).format(new Date()))
不使用任何库,以易于阅读和定制的方式获取所需格式的时间戳:
function timestamp(){
function pad(n) {return n<10 ? "0"+n : n}
d=new Date()
dash="-"
colon=":"
return d.getFullYear()+dash+
pad(d.getMonth()+1)+dash+
pad(d.getDate())+" "+
pad(d.getHours())+colon+
pad(d.getMinutes())+colon+
pad(d.getSeconds())
}
(如果你需要以UTC格式显示时间,只需更改函数调用。例如,“getMonth”变为“getUTCMonth”)
JavaScript库sugar.js(http://sugarjs.com/)具有格式化日期的功能。
示例:
Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')
$ npm install dateformat
$ dateformat --help
演示
var dateFormat = require('dateformat');
var now = new Date();
// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21
// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!
// You can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
...
var ts_hms = new Date();
console.log(
ts_hms.getFullYear() + '-' +
("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' +
("0" + (ts_hms.getDate())).slice(-2) + ' ' +
("0" + ts_hms.getHours()).slice(-2) + ':' +
("0" + ts_hms.getMinutes()).slice(-2) + ':' +
("0" + ts_hms.getSeconds()).slice(-2));
这看起来很杂乱,但使用JavaScript核心方法应该可以正常工作。
日期格式化最简单的方法是使用moment库。https://momentjs.com/
const moment = require('moment')
const current = moment().utc().format('Y-M-D H:M:S')
toISOString()
和 toUTCString()
。 - Bablu Ahmed
new Date().toUTCString()
? - hellboy