使用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");
我怎么做呢?
当前回答
易于阅读和自定义的方式,以获得所需格式的时间戳,无需使用任何库:
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")
其他回答
易于阅读和自定义的方式,以获得所需格式的时间戳,无需使用任何库:
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")
我需要一个简单的格式化库,不需要locale和语言支持。所以我修改了
http://www.mattkruse.com/javascript/date/date.js
并且使用它。参见https://github.com/adgang/atom-time/blob/master/lib/dateformat.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日期/时间:
有一个转换库:
npm install dateformat
然后写下你的要求:
var dateFormat = require('dateformat');
然后绑定值:
var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");
看到dateformat
这里有一个方便的香草单行(改编自此):
Var timestamp = new Date((dt = new Date()).getTime() - dt. gettimezoneoffset () * 60000) .toISOString () .replace (/ (. *), (. *) \ T . .* /, ' $ 1 $ 2 ') console.log(时间戳)
输出:2022-02-11 11:57:39