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

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

我怎么做呢?


当前回答

有一个转换库:

npm install dateformat

然后写下你的要求:

var dateFormat = require('dateformat');

然后绑定值:

var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");

看到dateformat

其他回答

你可以使用轻量级库Moment js

npm install moment

给图书馆打电话

var moments = require("moment");

现在转换成你需要的格式

moment().format('MMMM Do YYYY, h:mm:ss a');

更多格式和细节,你可以关注官方文档Moment js

这是我写的一个轻量级的简单日期格式库,可以在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

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

用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

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