How to check if today and specific date is same using moment.js?

Member

by dedrick , in category: Javascript , 8 months ago

How to check if today and specific date is same using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 8 months ago

@dedrick 

You can check if today's date is the same as a specific date using moment.js by creating two moment objects for today's date and the specific date, and then comparing them. Here's an example code snippet to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const moment = require('moment');

// Get today's date
const today = moment();

// Create a specific date
const specificDate = moment('2022-12-25', 'YYYY-MM-DD'); // Change this to the specific date you want to compare with

// Check if today is the same as the specific date
if (today.isSame(specificDate, 'day')) {
  console.log('Today is the same as the specific date');
} else {
  console.log('Today is not the same as the specific date');
}


In this code snippet, we first create moment objects for today's date and a specific date ('2022-12-25' in this case). We then use the isSame function to compare the two dates. The 'day' parameter specifies that we want to compare the dates at the day level. If the two dates are the same, the console will log "Today is the same as the specific date", otherwise it will log "Today is not the same as the specific date".