DEV Community

Cover image for Vanilla JavaScript Check if Date is in the Past
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript Check if Date is in the Past

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

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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!

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

Top comments (3)

Collapse
 
pavelloz profile image
Paweł Kowalski

Heh, my solution to the same problem:

var now = +new Date();

var past = +new Date('2020-05-20');
var future = +new Date('2021-05-20');

console.log(now > past);
console.log(now > future);

Comparing timestamps/epoch/integers ;-)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Just a point - your routine has a side effect of actually modifying the date you passed in... Seems unwise. Perhaps:

dateInPastArrow = (firstDate, secondDate) =>
  new Date(firstDate).setHours(0, 0, 0, 0) <= new Date(secondDate).setHours(0, 0, 0, 0); 
Collapse
 
savagepixie profile image
SavagePixie • Edited

Also, shouldn't the comparison operator be just less than? If it's equal it's not past but present (or, to be more precise concurrent with the second date, since that could be any point in time)