Now and then you need a JavaScript function to tell you if a date is in the past or future. You want to see if someone’s contract or whatever has passed as of today for example.
So let’s see how we can achieve this in Vanilla JavaScript
.
We will build a custom JS function for this so it will be reusable.
Check if a date is in the past JS code
In essence, we could use getTime()
to get the timestamp, but what happens for instance if someones contract must end on this day regardless of the time?
const dateInPast = function (firstDate, secondDate) {
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
return true;
}
return false;
};
const past = new Date('2020-05-20');
const today = new Date();
const future = new Date('2030-05-20');
dateInPast(past, today);
dateInPast(future, today);
Explanation of the evaluation if the date has passed
I’ve written down the full JavaScript function just to explain it better.
As you can see we define a dateInPast
function which accepts two dates.
We then check if the firstDate is smaller than or equal to the second Date.
If so, the date is in the past or today!
Then we reset the hours/minutes on it so it will be a general day.
Let’s now turn this into an arrow function for cleaner code:
dateInPastArrow = (firstDate, secondDate) =>
firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0);
console.log(dateInPastArrow(past, today));
console.log(dateInPastArrow(future, today));
As you can see: much cleaner code and easier to understand why a date is evaluated to be in the past or future!
Copy-paste or play with the Vanilla JS code in this Codepen
See the Pen Vanilla JavaScript Check if Date is Past by Chris Bongers (@rebelchris) on CodePen.
Thank you for reading, and let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter