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

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. The formatting can be done .toLocaleString():

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Jun-2020

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:

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.


Do you find this helpful?

Related articles