How to Check if a Date Refers to a Past Day in JavaScript
When working with dates in JavaScript, you may come across a scenario where you need to determine if a given date refers to a day in the past. Simply comparing dates using the getTime() method isn’t sufficient, as dates may have different times associated with them. This article will guide you through a solution to this problem.
To check if a date references a past day in JavaScript, you can use the following function:
1 | const isFirstDatePastSecondDate = (firstDate, secondDate) => { |
In this function, the setHours() method is used to set the time for both dates to 00:00:00. By doing so, the comparison will only consider the dates without taking the time into account.
Here’s a more concise version of the function using implicit return:
1 | const isFirstDatePastSecondDate = (firstDate, secondDate) => firstDate.setHours(0, 0, 0, 0) - secondDate.setHours(0, 0, 0, 0) < 0; |
To use this function, let’s consider an example where we compare yesterday’s date to today’s date:
1 | const today = new Date(); |
In the example above, we create two date objects - today and yesterday. We set the yesterday date to the previous day by using the setDate() method with a value of yesterday.getDate() - 1. Finally, we call the isFirstDatePastSecondDate function to check if yesterday is in the past compared to today, and vice versa.
By following this approach, you can accurately determine if a given date refers to a day in the past in JavaScript.
tags: [“JavaScript”, “date comparison”, “past day”, “getTime()”, “setHours()”]