最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Checking if date is greater than today - Stack Overflow

programmeradmin1浏览0评论

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. Try today.setHours(0, 0, 0, 0) to set the time to midnight. – phuzi Commented Jan 21, 2021 at 16:11
Add a ment  | 

2 Answers 2

Reset to default 3

Don'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

发布评论

评论列表(0)

  1. 暂无评论