Check if a Date is Between Two Dates in JavaScript

When we need to check if a given numerical value is greater than or less than the another value, we use the comparison operators(> and <).

Just like the numerical values, we can also use the comparison operators to check if a given date is less than or greater than the another date.

But before comparing, make sure that the dates are not in string format. If the dates are in string format, you have to first convert them into date objects using the Date() constructor and then do the comparison.

Example:

// Set start and end dates
const startDate = new Date('2021-10-25');
const endDate = new Date('2023-03-13');


let date = new Date('2022-11-15');


if(date > startDate && date < endDate){
    console.log('Date is between given dates');  // Output
}
else{
    console.log('Date is not between given dates');
}

Output:

Date is between given dates

In the above example, the given date 15 November 2022 lies between the date range 25 October 2021 – 13 March 2023, therefore, the code inside the if condition runs.


Check if a Date is Between Two Dates using getTime() Method

The date.getTime() method returns an integer representing the number of milliseconds since January 1, 1970.

For eg. if you apply the getTime() method on the current date-time object, it will return you the total number of milliseconds from January 1, 1970 till the current time.

const today = new Date();

console.log(today);  // Fri Nov 25 2022 22:24:58
console.log(today.getTime());  // 1669395298777

As the getTime() method returns a number, so we can use this number to compare the dates instead of comparing the date objects.

// Set start and end dates
const startDate = new Date('2021-10-25');
const endDate = new Date('2023-03-13');


let date = new Date('2022-11-15');


if(
    date.getTime() >= startDate.getTime() &&
    date.getTime() <= endDate.getTime() 
   ){
        console.log('Date is between given dates');  // Output
}
else{
    console.log('Date is not between given dates');
}

Output:

Date is between given dates

Conclusion

In this article, we learned two ways to check if a given date is between two dates using JavaScript.

The first approach is to create the date objects from the given date strings and then compare them using the comparison operators. If the given date object is greater than the start date and less than the end date, it’s between the two dates, otherwise not.

The second approach is to get the total number of milliseconds from all three dates using the getTime() method and compare them to check if the date lies in the given range.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.