[javascript] 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?

This question is related to javascript node.js date

The answer is


I needed a simple formatting library without the bells and whistles of locale and language support. So I modified

http://www.mattkruse.com/javascript/date/date.js

and used it. See https://github.com/adgang/atom-time/blob/master/lib/dateformat.js

The documentation is pretty clear.


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

Example:

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

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

new Date().toString("yyyyMMddHHmmss").
      replace(/T/, ' ').  
      replace(/\..+/, '') 

with .toString(), This becomes in format

replace(/T/, ' '). //replace T to ' ' 2017-01-15T...

replace(/..+/, '') //for ...13:50:16.1271

example, see var date and hour:

_x000D_
_x000D_
var date="2017-01-15T13:50:16.1271".toString("yyyyMMddHHmmss")._x000D_
                    replace(/T/, ' ').      _x000D_
                    replace(/\..+/, '');_x000D_
    _x000D_
                    var auxCopia=date.split(" ");_x000D_
                    date=auxCopia[0];_x000D_
                    var hour=auxCopia[1];_x000D_
_x000D_
console.log(date);_x000D_
console.log(hour);
_x000D_
_x000D_
_x000D_


I am using dateformat at Nodejs and angularjs, so good

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

Here's a lightweight library simple-date-format I've written, works both on node.js and in the browser

Install

  • Install with NPM
npm install @riversun/simple-date-format

or

  • Load directly(for browser),
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format/lib/simple-date-format.js"></script>

Load Library

  • ES6
import SimpleDateFormat from "@riversun/simple-date-format";
  • CommonJS (node.js)
const SimpleDateFormat = require('@riversun/simple-date-format');

Usage1

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"

Run on Pen

Usage2

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
console.log(sdf.format(date));//to be "2018-07-17T12:08:56+09:00"

Patterns for formatting

https://github.com/riversun/simple-date-format#pattern-of-the-date


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


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


Use the method provided in the Date object as follows:

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


Alternative #6233....

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

// 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:

enter image description here


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

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

appHelper.validateDates = function (start, end) {
    var returnval = false;

    var fd = new Date(start);
    var fdms = fd.getTime();
    var ed = new Date(end);
    var edms = ed.getTime();
    var cd = new Date();
    var cdms = cd.getTime();

    if (fdms >= edms) {
        returnval = false;
        console.log("step 1");
    }
    else if (cdms >= edms) {
        returnval = false;
        console.log("step 2");
    }
    else {
        returnval = true;
        console.log("step 3");
    }
    console.log("vall", returnval)
    return returnval;
}

I think this actually answers your question.

It is so annoying working with date/time in javascript. After a few gray hairs I figured out that is was actually pretty simple.

var date = new Date();
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();

var ampm = hours >= 12 ? 'pm' : 'am';
hours = ((hours + 11) % 12 + 1);//for 12 hour format

var str = month + "/" + day + "/" + year + " " + hours + ":" + min + ":" + sec + " " + ampm;
var now_utc =  Date.UTC(str);

Here is a fiddle


Check the code below and the link to MDN

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

// exact format
console.log(new Date().toISOString().replace('T', ' ').substring(0, 19))

// other formats
console.log(new Date().toUTCString())
console.log(new Date().toLocaleString('en-US'))
console.log(new Date().toString())
_x000D_
_x000D_
_x000D_


For date formatting the most easy way is using moment lib. https://momentjs.com/

const moment = require('moment')
const current = moment().utc().format('Y-M-D H:M:S')

Use x-date module which is one of sub-modules of x-class library ;

require('x-date') ; 
  //---
 new Date().format('yyyy-mm-dd HH:MM:ss')
  //'2016-07-17 18:12:37'
 new Date().format('ddd , yyyy-mm-dd HH:MM:ss')
  // 'Sun , 2016-07-17 18:12:51'
 new Date().format('dddd , yyyy-mm-dd HH:MM:ss')
 //'Sunday , 2016-07-17 18:12:58'
 new Date().format('dddd ddSS of mmm , yy')
  // 'Sunday 17thth +0300f Jul , 16'
 new Date().format('dddd ddS  mmm , yy')
 //'Sunday 17th  Jul , 16'

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!

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?