How to Format a JavaScript Date

Formatting a JavaScript date is a common thing. There are a date and time string everywhere on websites. A considerable number of application dates are formatted with JavaScript code.

There are some methods and libraries that are used to format dates. Let’s consider each of them separately.

Moment.js Method

Moment.js is one of the best date/time libraries. It is easy to use, well documented, and minified in size (20kb). It operates with both Node.js and JavaScript, which is great as you do not have to learn several date/time libraries for front-end and back-end programming.

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

Dateformat Method

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'

Date.toLocaleString() Method

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():

javascript dateformat method
const date = new Date(); const str = date.toLocaleString("en-us", { hour12: true, weekday: "short", hour: "2-digit", month: "long", year: "numeric", }); console.log(str);

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:

javascript Date.toLocaleString() method
function addLeadingZeros(n) { if (n <= 9) { return "0" + n; } return n } let currentDatetime = new Date() console.log(currentDatetime.toString()); let formattedDate = currentDatetime.getFullYear() + "-" + addLeadingZeros(currentDatetime.getMonth() + 1) + "-" + addLeadingZeros(currentDatetime.getDate()) + " " + addLeadingZeros(currentDatetime.getHours()) + ":" + addLeadingZeros(currentDatetime.getMinutes()) + ":" + addLeadingZeros(currentDatetime.getSeconds()) console.log(formattedDate);

The Date object is used for representing date and time in JavaScript. It includes both of them. As a rule, the months start from zero and end with 11. The weekdays are also counted starting from zero. In JavaScript, the dates might be subtracted and give their difference in milliseconds, as a Date is transformed into timestamp when converted to a number. Timestamps are in milliseconds, not seconds.