I’m looking for a method to assess two date values in JavaScript. Specifically, I want to check if one date is after or before the other, and ensure that neither of them are from the past. The date values will be obtained from input fields.
In JavaScript, you can compare two dates easily using the Date
object. First, ensure your date values are formatted correctly from the input fields. If you want to check whether one date is after or before the other and ensure neither is from the past, follow these steps:
-
Convert input values to
Date
objects:let date1 = new Date(document.getElementById('date1').value); let date2 = new Date(document.getElementById('date2').value);
-
Check if either date is in the past by comparing to the current date:
let today = new Date(); if (date1 < today || date2 < today) { console.log('One or both dates are in the past.'); }
-
Compare the two dates to see if one is after or before the other:
if (date1 > date2) { console.log('Date 1 is after Date 2'); } else if (date1 < date2) { console.log('Date 1 is before Date 2'); } else { console.log('Both dates are the same'); }
This approach is efficient and straightforward, leveraging JavaScript's built-in date functionality. It ensures you accurately assess the order of the dates while verifying neither is from the past.