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

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

我怎么做呢?


当前回答

我需要一个简单的格式化库,不需要locale和语言支持。所以我修改了

http://www.mattkruse.com/javascript/date/date.js

并且使用它。参见https://github.com/adgang/atom-time/blob/master/lib/dateformat.js

文档非常清楚。

其他回答

我在Nodejs和angularjs中使用dateformat,很好

安装

$ npm install dateformat
$ dateformat --help

demo

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
...

javascript库sugar.js (http://sugarjs.com/)有格式化日期的函数

例子:

Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')

从“日期格式”导入日期格式; var what = new Date()

<footer>
    <span>{props.data.footer_desc} <a href={props.data.footer_link}>{props.data.footer_text_link}</a> {" "}
    ({day = dateFormat(props.data.updatedAt, "yyyy")})
            </span>
</footer>

rodape

用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核心方法一起工作