You can check if a date is between two dates in JavaScript by comparing the dates using the getTime()
method, which returns the number of milliseconds since January 1, 1970, and checking if the date falls within the range.
Here is an example function that takes a date, a start date, and an end date as arguments and returns true
if the date falls between the start date and end date, and false
otherwise:
function isDateBetween(date, startDate, endDate) {
// Convert all dates to milliseconds since January 1, 1970
const dateMs = date.getTime();
const startDateMs = startDate.getTime();
const endDateMs = endDate.getTime();
// Check if the date is between the start date and end date
return (dateMs >= startDateMs && dateMs <= endDateMs);
}
In this function, we first convert all dates to milliseconds since January 1, 1970 using the getTime()
method.
We then compare the date in milliseconds to the start date and end date in milliseconds, and return true
if the date falls within the range (i.e. it is greater than or equal to the start date and less than or equal to the end date), and false
otherwise.
Here is an example usage of the function:
const date = new Date('2023-03-01');
const startDate = new Date('2023-02-28');
const endDate = new Date('2023-03-02');
console.log(isDateBetween(date, startDate, endDate)); // Output: true
In this example, we create a date
object for March 1, 2023, and define a startDate
object for February 28, 2023, and an endDate
object for March 2, 2023. We then call the isDateBetween
function with these three dates, and it returns true
because March 1, 2023 falls between February 28, 2023 and March 2, 2023.