使用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");
我怎么做呢?
当前回答
你可以使用轻量级库Moment js
npm install moment
给图书馆打电话
var moments = require("moment");
现在转换成你需要的格式
moment().format('MMMM Do YYYY, h:mm:ss a');
更多格式和细节,你可以关注官方文档Moment js
其他回答
替代# 6233…
将UTC偏移量添加到本地时间,然后使用Date对象的toLocaleDateString()方法将其转换为所需的格式:
// Using the current date/time
let now_local = new Date();
let now_utc = new Date();
// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())
// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';
// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));
我正在创建一个默认为本地时间的日期对象。我添加了UTC偏移量。我正在创建一个日期格式化对象。我正在以所需的格式显示UTC日期/时间:
对于日期格式,最简单的方法是使用moment lib。https://momentjs.com/
const moment = require('moment')
const current = moment().utc().format('Y-M-D H:M:S')
new Date().toString("yyyyMMddHHmmss").
replace(/T/, ' ').
replace(/\..+/, '')
使用.toString(),这将变成格式 replace(/T/, ' ')。//替换T到' ' 2017-01-15T… 替换(/ . .+/, ") //for…13:50:16.1271
示例:参见var date and hour:
var日期”=“2017-01-15T13:50:16 1271。”“yyyyMMddHHmmss”toString()。 代表(/T/, ')。 replace(/)。+ / -); var auxCopia =日期。斯普利特(“”); 鉴于= auxCopia [0]; var时光= auxCopia [1]; 游戏机。log(日期); 游戏机。log(时光”);
易于阅读和自定义的方式,以获得所需格式的时间戳,无需使用任何库:
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")
使用Date对象提供的方法,如下所示:
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核心方法一起工作