使用NodeJS,我想将Date格式化为以下字符串格式:

var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");

我怎么做呢?


当前回答

用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 Object, 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()))

如果你使用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(总是一件好事)。

使用x-date模块,它是x类库的子模块之一;

require('x-date') ; 
  //---
 new Date().format('yyyy-mm-dd HH:MM:ss')
  //'2016-07-17 18:12:37'
 new Date().format('ddd , yyyy-mm-dd HH:MM:ss')
  // 'Sun , 2016-07-17 18:12:51'
 new Date().format('dddd , yyyy-mm-dd HH:MM:ss')
 //'Sunday , 2016-07-17 18:12:58'
 new Date().format('dddd ddSS of mmm , yy')
  // 'Sunday 17thth +0300f Jul , 16'
 new Date().format('dddd ddS  mmm , yy')
 //'Sunday 17th  Jul , 16'
new Date(2015,1,3,15,30).toLocaleString()

//=> 2015-02-03 15:30:00
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(时光”);