Master Time Manipulation in JavaScript Using Moment.js

Joshua Hall

When I was learning JavaScript, dealing with time and dates seemed like such an unnecessary hassle. Why deal with milliseconds from the first day of 1970? Why put up with a clunky return value like 2019-06-24T13:12:41.044Z? Why is there no simple way of formatting or altering dates exactly as we would like? You would think that something as basic as time would have been optimized for ease of use long ago, but alas, that is not the case yet.

Here we are now, stranded, left to pick through the rubble that ECMA has left for us.

But not anymore…

Our savior has come, and it’s called Moment.js. (yes, I’m being overdramatic)

Installation

First, we must install it through npm (or Yarn, I won’t judge).

$ npm install moment

Or just use the handy CDN here, https://cdn.jsdelivr.net/npm/moment@2.24.0/min/moment.min.js

Basic Methods

  • moment() Store the desired date as a string or leave empty to save the current time/date
  • format() Configure the date using the character strings below.

Most Useful Formats

These are the strings that will be passed into format(). As you can tell the short versions tend to represent the shorthand dates and the long versions the longer, more formal versions.

  • YY and YYYY for single and four digit years like ‘19’ and ‘2019’
  • M and MM for single and double digit months like ‘6’ and ‘06’
  • MMM and MMMM for short and long month names like ‘Jan’ and ‘January’
  • D and Do for days of the month like ‘23’ and ‘23rd’
  • ddd and dddd for short and long forms of the week days like ‘Sun’ and ‘Sunday’
  • h for the hour of a 12 hour time system like ‘7’am/pm
  • m for minutes into the current hour like ‘26’
  • s for seconds into the current minute like ‘52’
  • a and A for lower and uppercase AM/PM

Examples

If you ever need to include text in the string, escape it with brackets []. Commas, colons, dashes, and other punctuation will work by default and don’t need to be escaped.

const moment = require('moment');
const now = moment();

console.log(now.format('MMMM-Do-YYYY'));
// >> June-23rd-2019

console.log(now.format('dddd, MMMM Do YYYY [at] h:m A'));
// >> Sunday, June 23rd 2019 at 7:37 PM

const then = moment('1984-08-21');
console.log(then.format('Do [of] MMMM, YYYY'));
// >> 21st of August, 1984

Date/Time Manipulations

We can do a lot more than just store and format dates, we can add or subtract units like years, days, or minutes as we please. It doesn’t matter if the unit string is plural or not.

  • add() Takes the number amount and the unit as a string; now.add(1, 'day')
  • subtract() Takes the number amount and the unit as a string; now.subtract(5, 'years')

Examples

When you need to do multiple operations you can either chain the functions together like now.add(1, 'year').add(4, 'days') or pass in an object literal like now.add({ years: 1, days: 4 }). You can also chain different functions that are being passed in objects, for handling multiple different operations.

const now = moment();

console.log(now.add(5, 'years').subtract(9, 'years').add(4, 'days').format('Do [of] MMMM, YYYY'));
// >> 3rd of July, 2015

console.log(now.add({ years: 6, days: 12 }).subtract({ years: 7 }).format('Do [of] MMMM, YYYY'));
// >> 11th of July, 2018

Comparisons

Comparison functions are useful whenever you need to show a dynamic formatted message like ‘edited 1 hour ago’ or set up some conditional logic.

  • to() and from() Return a formatted string for how distant in time something was or is. They essentially do the same thing but differ slightly in the message they return.
  • isBefore(), isAfter(), isBetween, and isSame() return booleans.
  • isSameOrBefore() and isSameOrAfter() return booleans.
const now = moment();
const then = moment('1984-08-21');

console.log(now.to(then));
// >> 35 years ago

console.log(then.to(now));
// >> in 35 years

if (then.isBefore(now)) console.log('this is the future');
// >> this is the future

Example

Here’s a basic example of what you can build with Moment.js. It’s just an input that tells you what day of the week the given date falls on (I used a little Materialize css to snazz it up a bit).

See the Pen Day Calculator by Alligator.io (@alligatorio) on CodePen.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#