Sometimes, we want to compare 2 dates in format DD/MM/YYYY with JavaScript.
In this article, we’ll look at how to compare 2 dates in format DD/MM/YYYY with JavaScript.
How to compare 2 dates in format DD/MM/YYYY with JavaScript?
To compare 2 dates in format DD/MM/YYYY with JavaScript, we can convert each date string to a date.
For instance, we write:
const date1 = '25/02/1985';
const date2 = '26/02/1985';
const convertToDate = (d) => {
const [day, month, year] = d.split("/");
return new Date(year, month - 1, day);
}
console.log(convertToDate(date1) > convertToDate(date2))
to define the convertToDate
function that takes the date string d
.
In it, we call split
with '/'
to split the string by the slashes.
And then we destructure the date parts from the returned array and put them into the Date
constructor.
We’ve to subtract month
by 1 since JavaScript date’s months are zero-based.
Next, we call convertToDate
with date1
and date2
and compare the 2 values.
Since date1
is earlier than date2
, the console log should log false
.
Conclusion
To compare 2 dates in format DD/MM/YYYY with JavaScript, we can convert each date string to a date.