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


Using NodeJS, 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?

9/12/2018 8:20:00 PM

Accepted Answer

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

12/11/2013 3:38:17 PM

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow