Javascript 如何使用NodeJS将UTC日期格式化为`YYYY-MM-DD hh:mm:ss`字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10645994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:19:27  来源:igfitidea点击:

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

javascriptnode.jsdate

提问by Tampa

Using NodeJS, I want to format a Dateinto the following string format:

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

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

How do I do that?

我怎么做?

回答by chbrown

If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOStringmethod. You're asking for a slight modification of ISO8601:

如果你使用 Node.js,你肯定有 EcmaScript 5,所以 Date 有一个toISOString方法。您要求对 ISO8601 稍作修改:

new Date().toISOString()
> '2012-11-04T14:51:06.157Z'

So just cut a few things out, and you're set:

所以只要删掉一些东西,你就准备好了:

new Date().toISOString().
  replace(/T/, ' ').      // replace T with a space
  replace(/\..+/, '')     // delete the dot and everything after
> '2012-11-04 14:55:45'

Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

或者,在一行中: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).

ISO8601 必须是 UTC(也由第一个结果的尾随 Z 表示),因此默认情况下您会获得 UTC(总是一件好事)。

回答by Julian Knight

UPDATE 2017-03-29: Added date-fns, some notes on Moment and Datejs
UPDATE 2016-09-14: Added SugarJS which seems to have some excellent date/time functions.

2017-03-29 更新:添加了 date-fns、关于 Moment 和 Datejs 的一些注释
2016-09-14 更新:添加了 SugarJS,它似乎具有一些出色的日期/时间功能。



OK, since no one has actually provided an actual answer, here is mine.

好的,因为没有人真正提供过实际的答案,这里是我的。

A library is certainly the best bet for handling dates and times in a standard way. There are lots of edge cases in date/time calculations so it is useful to be able to hand-off the development to a library.

图书馆无疑是以标准方式处理日期和时间的最佳选择。日期/时间计算中有很多边缘情况,因此能够将开发移交给库很有用。

Here is a list of the main Node compatible time formatting libraries:

以下是主要的 Node 兼容时间格式库的列表:

  • Moment.js[thanks to Mustafa] "A lightweight (4.3k) javascript date library for parsing, manipulating, and formatting dates" - Includes internationalization, calculations and relative date formats - Update 2017-03-29: Not quite so light-weight any more but still the most comprehensive solution, especially if you need timezone support.
  • date-fns[added 2017-03-29, thanks to Fractalf] Small, fast, works with standard JS date objects. Great alternative to Moment if you don't need timezone support.
  • SugarJS- A general helper library adding much needed features to JavaScripts built-in object types. Includes some excellent looking date/time capabilities.
  • strftime- Just what it says, nice and simple
  • dateutil- This is the one I used to use before MomentJS
  • node-formatdate
  • TimeTraveller- "Time Traveller provides a set of utility methods to deal with dates. From adding and subtracting, to formatting. Time Traveller only extends date objects that it creates, without polluting the global namespace."
  • Tempus[thanks to Dan D] - UPDATE: this can also be used with Node and deployed with npm, see the docs
  • Moment.js[感谢 Mustafa] “用于解析、操作和格式化日期的轻量级 (4.3k) javascript 日期库” - 包括国际化、计算和相关日期格式 -更新 2017-03-29:不太轻量级更多但仍然是最全面的解决方案,特别是如果您需要时区支持。
  • date-fns[ 2017-03-29 添加,感谢 Fractalf] 小巧、快速,适用于标准 JS 日期对象。如果您不需要时区支持,则是 Moment 的绝佳替代品。
  • SugarJS- 一个通用的辅助库,为 JavaScript 的内置对象类型添加了急需的功能。包括一些出色的日期/时间功能。
  • strftime- 正如它所说的那样,漂亮而简单
  • dateutil- 这是我在 MomentJS 之前使用过的
  • 节点格式日期
  • TimeTraveller- “Time Traveler 提供了一组实用方法来处理日期。从加法和减法到格式化。TimeTraveler 只扩展它创建的日期对象,而不会污染全局命名空间。”
  • Tempus[感谢 Dan D] - 更新:这也可以与 Node 一起使用并与 npm 一起部署,请参阅文档

There are also non-Node libraries:

还有非节点库:

  • Datejs[thanks to Peter Olson] - not packaged in npm or GitHub so not quite so easy to use with Node - not really recommended as not updated since 2007!
  • Datejs[感谢 Peter Olson] - 没有打包在 npm 或 GitHub 中,所以不太容易与 Node 一起使用 - 不推荐,因为自 2007 年以来没有更新!

回答by Onder OZCAN

There's a library for conversion:

有一个用于转换的库:

npm install dateformat

Then write your requirement:

然后写出你的需求:

var dateFormat = require('dateformat');

Then bind the value:

然后绑定值:

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

see dateformat

见日期格式

回答by HBP

I have nothing against libraries in general. In this case a general purpose library seems overkill, unless other parts of the application process dates heavily.

我一般不反对图书馆。在这种情况下,通用库似乎过大了,除非申请过程的其他部分过时。

Writing small utility functions such as this is also a useful exercise for both beginning and accomplished programmers alike and can be a learning experience for the novices amongst us.

编写像这样的小型实用函数对于初学者和有经验的程序员来说也是一个有用的练习,并且可以成为我们中间的新手的学习经验。

function dateFormat (date, fstr, utc) {
  utc = utc ? 'getUTC' : 'get';
  return fstr.replace (/%[YmdHMS]/g, function (m) {
    switch (m) {
    case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
    case '%m': m = 1 + date[utc + 'Month'] (); break;
    case '%d': m = date[utc + 'Date'] (); break;
    case '%H': m = date[utc + 'Hours'] (); break;
    case '%M': m = date[utc + 'Minutes'] (); break;
    case '%S': m = date[utc + 'Seconds'] (); break;
    default: return m.slice (1); // unknown code, remove %
    }
    // add leading zero if required
    return ('0' + m).slice (-2);
  });
}

/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns 
   "2012-05-18 05:37:21"  */

回答by Mtl Dev

Easily readable and customisable way to get a timestamp in your desired format, without use of any library:

以您想要的格式获取时间戳的易于阅读和可定制的方式,无需使用任何库:

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())
}

(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth")

(如果您需要 UTC 格式的时间,则只需更改函数调用。例如“getMonth”变为“getUTCMonth”)

回答by David Miró

The javascript library sugar.js (http://sugarjs.com/) has functions to format dates

javascript 库 Sugar.js ( http://sugarjs.com/) 具有格式化日期的功能

Example:

例子:

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

回答by jpmonette

Use the method provided in the Date object as follows:

使用 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));

It looks really dirty, but it should work fine with JavaScript core methods

它看起来很脏,但它应该适用于 JavaScript 核心方法

回答by Tính Ng? Quang

I am using dateformatat Nodejs and angularjs, so good

我在 Nodejs 和 angularjs 上使用dateformat,太好了

install

安装

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

回答by gest

new Date(2015,1,3,15,30).toLocaleString()

//=> 2015-02-03 15:30:00

回答by Adam

Alternative #6233....

替代方案 #6233....

Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString()method of the Dateobject:

将UTC偏移量添加到本地时间,然后使用对象的toLocaleDateString()方法将其转换为所需的格式Date

// 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));

I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:

我正在创建一个默认为本地时间的日期对象。我正在向它添加 UTC 偏移量。我正在创建一个日期格式对象。我以所需的格式显示 UTC 日期/时间:

enter image description here

在此处输入图片说明