Node.js - How to format a date string in UTC

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

Using Node.js, I want to format a Date into the following string format:

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

How do I do that?

回答1:

If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of 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(/\..+/, '')

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



回答2:

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.


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:

  • 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

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!


回答3:

There's a library for conversion:

npm install dateformat

Then write your requirement:

var dateFormat = require('dateformat');

Then bind the value:

var day=dateFormat(result.request_date, "yyyy-mm-dd h:MM:ss");

see dateformat



回答4:

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"  */


回答5:

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

Example:

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


回答6:

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        
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!