Date Validation and Comparison with Moment.js

Installing Moment.js:

npm install moment

Importing Moment.js:

import moment from 'moment';

Checking if a Date is Valid:

One common task when working with dates is validating whether a given date is in a valid format. Moment.js simplifies this process using its parsing functionality.

const dateStr = '2022-04-30';
const isValid = moment(dateStr, 'YYYY-MM-DD', true).isValid();
console.log(isValid); // Output: true

Comparing Dates:

Moment.js makes date comparison straightforward with its built-in comparison functions. Let’s compare two dates:

const date1 = moment('2022-04-30');
const date2 = moment('2022-05-01');

console.log(date1.isBefore(date2)); // Output: true
console.log(date1.isSame(date2));  // Output: false
console.log(date1.isAfter(date2)); // Output: false

Calculating Durations:

Moment.js also simplifies the calculation of durations between dates. Let’s calculate the difference in days between two dates:

const startDate = moment('2022-04-30');
const endDate = moment('2022-05-05');

const durationInDays = endDate.diff(startDate, 'days');
console.log(durationInDays); // Output: 5

Leave a comment

Your email address will not be published. Required fields are marked *