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. In case of browser-side datetime will extend the Date object to have a .format() method:
today = new Date(); today.format('dd-m-yy'); // Returns '02-8-16'
However, it works differently with the Node.js version. 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. The formatting can be done .toLocaleString():
let today = new Date(); today.toLocaleFormat('%d-%b-%Y'); // 30-Jun-2020
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: