Trying out a Jquery to confirm if date selected is equal to today or greater than. If i select today, it return it as the day selected is less than today. Selecting previous day works well but selecting today returns less than. Any tip.
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.getTime()) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
Trying out a Jquery to confirm if date selected is equal to today or greater than. If i select today, it return it as the day selected is less than today. Selecting previous day works well but selecting today returns less than. Any tip.
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.getTime()) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
Share
Improve this question
asked Jan 21, 2021 at 16:05
uthumvcuthumvc
1551 silver badge13 bronze badges
1
-
new Date()
will include the current time not just the date. Trytoday.setHours(0, 0, 0, 0)
to set the time to midnight. – phuzi Commented Jan 21, 2021 at 16:11
2 Answers
Reset to default 3Don't forget that new Date()
will include the current time as well. You'll need to remove that time ponent with today.setHours(0,0,0,0)
for the parison to be correct.
Also, setHours()
returns the underlying value like getTime()
so you can do
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.setHours(0,0,0,0)) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
In response to the ment about adding 20 days:
This is a little more detailed but is fairly easy.
var today = new Date();
var plus20Days = new Date(today.setDate(today.getDate() + 20));
again you can then use setHours()
to reset the time ponent.
new Date()
considers time too, not only the date. I think the easiest way to achieve this is to pare years, months and days by using respectively getFullYear() , getMonth() , getDate().
Check all the methods that manipulate js Date here https://developer.mozilla/it/docs/Web/JavaScript/Reference/Global_Objects/Date