How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?
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).
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!
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