There are some methods and libraries that are used to format dates. Let’s consider each of them separately.
moment().format('YYYY-MM-DD HH:m:s'); // now() -> 2020-03-20 14:32:20 moment("20161031", "YYYYMMDD").fromNow(); // 3 years ago moment("20170620", "YYYYMMDD").fromNow(); // 3 years ago moment().startOf('day').fromNow(); // 11 hours ago moment().endOf('day').fromNow(); // in 13 hours
The .format() method constructs a string of tokens that refer to a particular component of date (like day, month, minute, or am/pm).
The dateformat is similar to the previous method in a way that it formats dates using token strings.
However, it works differently with the Node.jsversion. You should use dateformat as a method and pass the Date object:
const dateformat = require('dateformat'); let now = new Date(); dateformat(now, 'dddd, mmmm dS, yyyy, h:MM:ss TT'); 'Tuesday, Feb 2nd, 2020, 4:30:20 PM'
This is a non-standard method, but sometimes, this might be the only choice. This method is only supported in later versions of some browsers. Nevertheless, in the case of Node, it can be a good choice. Unlike the two above methods, Date.toLocaleString() does not use token strings. It uses an options object where each part of the date can be configured. These options are very wide and the detailed description of them is out of scope of this page. The formatting can be done by .toLocaleString():
How to Add Zeros in DateTime
If the hour, minute, and seconds are less than 9, you should do extra works for adding leading zeros in DateTime. You should add a custom method to append leading zeros in DateTime: