Vanilla JavaScript Check if Date is in the Past

— 3 minute read


Now and then you need this function, you want to see if someone's contract or whatever is passed as of today. So let's see how we can achieve this in JavaScript. We will build a custom function for this so it will be reusable.

JavaScript Check if a Date is in the Past permalink

In essence we could use getTime() to get the timestamp, but for instance someones contract must end on this day regardless of the time?

var dateInPast = function(firstDate, secondDate) {
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
return true;

return false;

var past = new Date('2020-05-20');
var today = new Date();
var future = new Date('2030-05-20');
dateInPast(past, today);
dateInPast(future, today);

I've written down the full 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 secondDate. If so it is in the past or today! 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 and quicker!

Feel free to play with 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! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter