Compare Two Dates in JavaScript
Comparing two dates in JavaScript is a fundamental task that can be achieved using the Date
object. This short guide will walk you through the simplest way to compare two dates.
How to
First, you need to have two dates that you want to compare.
Create two Date
objects for these dates.
const date1 = new Date('2024-04-20'); const date2 = new Date('2024-04-21');
To compare the two dates, convert them into milliseconds since the Unix Epoch (January 1, 1970) using the getTime()
method.
const time1 = date1.getTime(); const time2 = date2.getTime();
Now, you can compare the milliseconds to determine if one date is before, after, or the same as the other date using the usual operators in JS since it's now just comparing numbers:
// Check if the first date is before the second date if (time1 < time2) { console.log('Date1 is before Date2.'); } // Check if the first date is after the second date if (time1 > time2) { console.log('Date1 is after Date2.'); } // Check if both dates are the same if (time1 === time2) { console.log('Both dates are the same.'); }
TLDR
Now Here's a little function you can copy and paste to tie it all together:
function compareDates(dateStr1, dateStr2) { // Create Date objects from the input strings const date1 = new Date(dateStr1); const date2 = new Date(dateStr2); // Convert the dates to milliseconds const time1 = date1.getTime(); const time2 = date2.getTime(); // Compare the milliseconds and return a descriptive message if (time1 < time2) { return 'The first date is before the second date.'; } else if (time1 > time2) { return 'The first date is after the second date.'; } else { return 'Both dates are the same.'; } } // Example usage: console.log(compareDates('2024-04-20', '2024-04-21')); // The first date is before the second date. console.log(compareDates('2024-04-21', '2024-04-20')); // The first date is after the second date. console.log(compareDates('2024-04-20', '2024-04-20')); // Both dates are the same.