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?


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

Solution 2:

UPDATE 2021-10-06: Added Day.js and remove spurious edit by @ashleedawg
UPDATE 2021-04-07: Luxon added by @Tampa.
UPDATE 2021-02-28: It should now be noted that Moment.js is no longer being actively developed. It won't disappear in a hurry because it is embedded in so many other things. The website has some recommendations for alternatives and an explanation of why.
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:

  • Day.js [added 2021-10-06] "Fast 2kB alternative to Moment.js with the same modern API"
  • Luxon [added 2017-03-29, thanks to Tampa] "A powerful, modern, and friendly wrapper for JavaScript dates and times." - MomentJS rebuilt from the ground up with immutable types, chaining and much more.
  • 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. - Update 2021-02-28: No longer in active development.
  • 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!

Solution 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(new Date(), "yyyy-mm-dd h:MM:ss");

see dateformat