'How to check date within two given dates and return true or false
I am trying to verify whether the given date is within the two dates. I tried based on online resources I find using below methods whatever I tried code returning False, so could someone please let me know how we can achieve this. Thanks
// *For example* - Datetocheck = today's date
Startdate = '09/05/2022'
Enddate ='31/05/2022'
var TodayDate = new Date();
//var date = now.toLocaleDateString();
var dd = String(TodayDate.getDate()).padStart(2, '0');
var mm = String(TodayDate.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = TodayDate.getFullYear();
TodayDate = dd + '/' + mm + '/' + yyyy;
if(dateStart!=null&&dateStart!=undefined){
var year=dateStart.getFullYear();
var month=(dateStart.getMonth()+1);
var day=dateStart.getDate();
var startdate = day + '/' + month + '/' + year;
}
if(dateEnd!=null&&dateEnd!=undefined){
var year1=dateEnd.getFullYear();
var month1=(dateEnd.getMonth()+1);
var day1=dateEnd.getDate();
var enddate = day1 + '/' + month1 + '/' + year1;
}
if(TodayDate > startdate && TodayDate < enddate {
return true;
// alert("Within the range");
}else{
return false;
// alert("Outside the range");
}
Solution 1:[1]
You're comparing strings. If you used YYYY-MM-DD order, that would work, but since you're using DD/MM/YYYY order, it doesn't. The strings are compared "alphabetically" (including non-letters being ordered the way they are in the character set), which means that, for example, the 20th of any month will be "greater than" the 10th of any month, even if the two months are in the opposite order within the year and/or the dates are years apart, just because 2 comes after 1.
I would just use Date objects directly.
const startDate = new Date(2022,4,9); // 0=January, so May=4
const endDate = new Date(2022,4,31);
let todayDate = new Date();
if (startDate <= todayDate && todayDate <= endDate) {
console.log("In range.");
}
Also, above I'm doing a test and then logging a message if the test is true, but if you want a function that just returns true or false, you don't need an if statement. Just return the value of the boolean expression itself:
return startDate <= todayDate && todayDate <= endDate;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
