Open In App

How To Compare Only Date In Moment.js?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Moment.js, date manipulation and parsing can be done efficiently. Along with this, the library provides ways to compare only the date portion of two date objects, ignoring the time component. Methods like startOf, isSame, and formatting techniques enable you to focus solely on the date part for accurate comparisons.

Run the below command before running the code in your local system:

npm i moment

1. Using Date Comparison and format

In this approach, we are using the format method to convert both date1 and date2 to strings in the 'YYYY-MM-DD' format, which represents only the date part of each moment object. By comparing these formatted date strings, we determine if the two dates are the same, ignoring the time component.

Example: The below example uses Date Comparison and format to compare only dates in moment.js.

JavaScript
// script.js

const moment = require("moment");
const date1 = moment("2024-07-24T08:00:00");
const date2 = moment("2024-07-24T14:30:00");
const res = date1.format("YYYY-MM-DD") === date2.format("YYYY-MM-DD");
console.log(`Are dates the same? ${res}`);

Output:

Are dates the same? true

2. Using isSame method

In this approach, the isSame method is used with the 'day' unit to compare date1 and date2. This method focuses on the date part of each moment object, ignoring any differences in time. By comparing using 'day', it determines if both dates fall on the same calendar day, which makes sure that only the date is considered in the comparison.

Example: The below example uses isSame to compare only date in moment.js.

JavaScript
// script.js

const moment = require("moment");
const date1 = moment("2024-07-24T08:00:00");
const date2 = moment("2024-07-24T14:30:00");
const res = date1.isSame(date2, "day");
console.log(`Are dates the same? ${res}`);

Output:

Are dates the same? true

3. Using startOf and diff

In this approach, we use the startOf method to set both date1 and date2 to the start of their respective days, removing any time component. We then calculate the difference in days between these adjusted dates using the diff method. By checking if this difference is zero, we determine if both dates are on the same calendar day.

Example: The below example uses startOf and diff to compare only date in moment.js.

JavaScript
// script.js

const moment = require("moment");
const date1 = moment("2024-07-24T08:00:00");
const date2 = moment("2024-07-25T14:30:00");
const startOfDay1 = date1.startOf("day");
const startOfDay2 = date2.startOf("day");
const dayDiff = startOfDay1.diff(startOfDay2, "days");
const res = dayDiff === 0;
console.log(`Are dates the same? ${res}`);

Output:

Are dates the same? false



Next Article

Similar Reads