使用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");
我怎么做呢?
当前回答
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(时光”);
其他回答
用Date就可以很容易地解决这个问题。
function getDateAndTime(time: Date) {
const date = time.toLocaleDateString('pt-BR', {
timeZone: 'America/Sao_Paulo',
});
const hour = time.toLocaleTimeString('pt-BR', {
timeZone: 'America/Sao_Paulo',
});
return `${date} ${hour}`;
}
这是为了显示:// 10/31/22 11:13:25
使用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核心方法一起工作
有一个转换库:
npm install dateformat
然后写下你的要求:
var dateFormat = require('dateformat');
然后绑定值:
var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");
看到dateformat
如果你使用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(总是一件好事)。
这是我写的一个轻量级的简单日期格式库,可以在node.js和浏览器上运行
安装
使用NPM安装
npm install @riversun/simple-date-format
or
直接加载(浏览器),
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format/lib/simple-date-format.js"></script>
加载库
ES6
import SimpleDateFormat from "@riversun/simple-date-format";
CommonJS node.js)
const SimpleDateFormat = require('@riversun/simple-date-format');
Usage1
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"
用钢笔跑
Usage2
const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
console.log(sdf.format(date));//to be "2018-07-17T12:08:56+09:00"
格式化模式
https://github.com/riversun/simple-date-format#pattern-of-the-date