Skip to content

[Javascript] Moment (part 1): Comparison

Posted on:September 25, 2020 at 03:20 PM

In this series, I will list all of use cases with MomentJS that we can meet in project. In this post, we talk about dates comparison, let’s started!

** Note: I used Javascript ES6 for code in this post.

Table of contents

Open Table of contents

Getting start with moment()

Moment is a popular JavaScript library for working with dates. Moment makes it easy to add, subtract, and format dates.

npm install moment
// or
yarn add moment
import moment from "moment";
moment().format();

Get the object of current date

const nowMoment = moment();
const yesterday = moment().subtract(1, "days");
const n = 7;
const prevDays = moment().subtract(n, "days");
const n = 7;
const nextnDays = moment().add(n, "days");
const tomorrow = moment().add(1, "days");
// We want to convert "12/14/2019"
// with format 'MM/DD/YYYY' to moment object
const dateString = "12/14/2019";
const dateMoment = moment(dateString, "MM/DD/YYYY");

Check a date is BEFORE an other date

Check if 12/14/2019 is before 12/14/2019:

const firstDateString = "12/14/2019";
const secondDateString = "12/21/2019";
const format = "MM/DD/YYYY";

const isFirstBeforeSecond = moment(firstDateString, format).isBefore(
  moment(secondDateString, format)
);

// Should be 'true'
console.log("Is BEFORE:", isFirstBeforeSecond);

Check a date is AFTER an other date

Check if 12/14/2019 is after 12/21/2019:

const firstDateString = '12/14/2019';
const secondDateString = '12/21/2019;
const format = 'MM/DD/YYYY';
const isFirstAfterSecond = moment(firstDateString, format).isAfter(moment(secondDateString, format));

// Should be 'fasle'
console.log('Is AFTER:', isFirstAfterSecond);

Check a date is BETWEEN two dates (a dates range)

Check if 12/14/2019 is between 12/02/2019 – 12/21/2019:

const checkingDate = '12/14/2019';
const startDateRange = '12/02/2019;
const endDateRange = '12/21/2019';
const format = 'MM/DD/YYYY';

const momentCheckingDate = moment(checkingDate, format);
const momentDateRange = {
  start: moment(startDateRange, format),
  end: moment(endDateRange, format)
};

const isBetween = momentCheckingDate.isBefore(momentDateRange.end) && momentCheckingDate.isAfter(momentDateRange.start);

// Should return 'true'
console.log('Is between:', isBetween);

Check two dates is same

Check if 11/21/2019 is same with 11/21/2019:

const checkingDate = '11/21/2019';
const comparingDate = '11/21/2019;
const format = 'MM/DD/YYYY';

const momentCheckingDate = moment(checkingDate, format);
const momentComparingDate = moment(comparingDate, format);

const isSame = momentCheckingDate.isSame(momentComparingDate);

// Should return 'true'
console.log('Is same:', isSame);