How to Format Date in JavaScript with Moment.JS

Let’s admit it: we do not like to work with dates and times in our applications. But, nothing we can do about it: the rest of the world relies on this method of temporal location. But you can make your life a lot easier by using special libraries, such as moment.js.

What is MomentJS?

MomentJS is an all-in-one solution for date time processing in your JavaScript app. It lets you create timestamps, modify them (add, subtract, etc), query them (is one before another), and display them in a variety of human-readable formats. It has a very easy and straightforward API and is pretty much an industry standard for date-related tasks in JavaScript applications.

Install MomentJS

You can install it using your package manager of choice:

npm i -S momentjs

Or

yarn add momentjs

If you are not using a package manager, you can just include the script directly in HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

Then, it would be available to import like this:

const moment = require('momentjs');
// or
import moment from 'momentjs';

If you are including the script in HTML, the moment object will be available globally, so you do not have to import it.

Convert time

To output time in a human-readable format, you first have to convert it to moment object. If you are getting the timestamp from server, it has to be an ISO-compliant date string, or a Unix timestamp in milliseconds:

const timestamp = await getTimeFromServer();
const momentTimestamp = moment(timestamp);
console.log(momentTimestamp.format()); // 2020-09-08T08:02:17-05:00

If you are creating timestamps using built-in new Date(), you can also use it to create moment objects:

const timestamp = new Date();
const momentTimestamp = moment(timestamp);

If you want to create a moment object using current date and time, just call moment() without any arguments.

Format time

Moment provides a simple interface for formatting time. The only function you need is format, which accepts a string as a template. Use it like this:

moment().format(); // "2020-06-05T12:28:46-04:00"

moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); 
// "Friday, June 5th 2020, 12:29:07 pm"

moment().format("ddd, hA"); // "Fri, 12PM"

Here is a list of common formatting tokens you can use in format():

MMonth: 1, 2, 3, … 12
MMMonth: 01, 02, 03, … 12
MMMMonth: Jan, Feb, … Dec
DDay: 1, 2, 3, … 31
DDDay: 01, 02, 03 … 31
dddDay: Sun, Mon, … Sat
YYYear: 70, 71, 72, …
YYYYYear: 1970, 1971, …
AAM/PM
h, hhHour in 12h format with and without trailing zeros
H, HHHour in 24h format with and without trailing zeros
m, mmMinutes with and without trailing zeros
s, ssSeconds with and without trailing zeros

Additionally, there are a couple of handy functions that can make formatting even easier. For example, if you need to display a last seen status, you can use the fromNow function:

const almostNow = moment().subtract(15, 'minutes');
const yesterday = moment().subtract(1, 'day').
const monthAgo = moment().subtract(1, 'month');

console.log(almostNow.fromNow()); // 15 minutes ago
console.log(yesterday.fromNow()); // a day ago
console.log(monthAgo.fromNow()); // a month ago

Similarly, there is a function toNow() which does the opposite.

Manipulate time

Formatting time is not the only strength of MomenJS. It can also manipulate time in many ways with an easy interface. For example, here is how you can change values directly:

const jesusBday = moment()
  .hour(1)
  .day(1)
  .month(1)
  .year(1);

Surely, there are easier ways to manipulate time for different use cases. For example, you can add or subtract:

const past = moment().subtract(2, 'month'); // To past
const future = moment().add(1, 'year'); // Back to future

For the second argument, you can provide any of the following:

  • years
  • quarters
  • months
  • weeks
  • days
  • hours
  • minutes
  • seconds
  • milliseconds

Lastly, you can fast forward times. Suppose, you need to get the timestamp of the beginning of the next month (or next year). For this, you can use the endOf function:

const today = moment();
const nextMon = moment().endOf('month');
// nextMon is now set to the ending of the current month
// 1 millisecond before that, to be precise

Surely, there is a function startOf as well:

const today = moment();
const lastNewYear = moment().startOf('year');
// lastNewYear is set to the first millisecond
// of the current year

Query time

What good is modifying the time if you cannot tell anything about it? MomenJS has a couple of functions that will help you with that. Firstly, there is the isBefore and isAfter: pretty much self-explanatory:

const now = moment();
const then = moment().add(1, 'day');

console.log(now.isAfter(then)); // false
console.log(then.isAfter(now)); // true

console.log(now.isBefore(then)); // true
console.log(then.isBefore(now)); // false

Additionally, there are non-strict versions of these functions: isSameOrBefore and isSameOrAfter. Another function worth knowing is isBetween:

const now = moment();
const past = moment().subtract(1, 'day');
const future = moment().add(1, 'day');

console.log(now.isBetween(past, future)); // true
console.log(past.isBetween(now, future)); // false

And, lastly, the max and min functions. They do exactly what you expect: return the minimum or maximum from a list of moments:

const now = moment();
const past = moment().subtract(1, 'year');
const future = moment().add(1, 'year');

console.log(moment.min(now, past, future).year()); // 2019
console.log(moment.max(now, past, future).year()); // 2021

Closing notes

Thank you for reading, I hope you liked this article. Stay subscribed for more interesting content on JavaScript and Software Development!

Resources

Get new content delivered to your mailbox:

leave a comment