如何将当前日期与未来日期进行比较并在 javascript 中对其进行验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34070628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:12:29  来源:igfitidea点击:

how to compare current date to a future date and validate it in javascript

javascriptvalidationdate

提问by iyke

`

`

`

`

I have a date text field in mm/dd/yyyy format. When a date is entered, I'd like to validate it to make sure the date is 2 months greater than the current date. If not, I'd like to display a message to notifying the user the date is less then 2 months but user can still proceed with filling the form after the notification.

我有一个 mm/dd/yyyy 格式的日期文本字段。输入日期后,我想对其进行验证以确保该日期比当前日期大 2 个月。如果没有,我想显示一条消息,通知用户日期不到 2 个月,但用户仍然可以在收到通知后继续填写表格。

Below is the form i want to add the function to.

下面是我想向其中添加功能的表单。

回答by Afroza Yasmin

If you used javascript then lets try to this one, It may help you.

如果您使用过 javascript,那么让我们尝试一下,它可能对您有所帮助。

<script type="text/javascript">

var date = new Date();
var month = date.getMonth()+1;
var day = date.getDay();
var year = date.getYear();

var newdate = new Date(year,month,day);

mydate=new Date('2011-04-11');

console.log(newdate);
console.log(mydate)

if(newdate > mydate)
{
    alert("greater");
}
else
{
    alert("smaller")
}


</script>

回答by Chandan

If your date is in mm/dd/yyyyformat in string then you can use the following method. It will return true if date is 2 months greater than the current date and false otherwise -

如果您的日期是mm/dd/yyyy字符串格式,那么您可以使用以下方法。如果日期比当前日期大 2 个月,它将返回 true,否则返回 false -

 // dateString in "mm/dd/yyyy" string format
 function checkMonth(dateString)      
 {
    var enteredMS = new Date(dateString).getTime();
    var currentMS = new Date().getTime();
    var twoMonthMS = new Date(new Date().setMonth(new Date().getMonth() + 2)).getTime();

    if(enteredMS >= twoMonthMS)
    {
       return true;
    }
    return false;
 }

Invoke this as checkMonth("03/12/2016");

调用它作为 checkMonth("03/12/2016");

回答by Basilin Joe

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2); // prints false (wrong!) 
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true  (wrong!)
console.log(d1 !== d2); // prints true  (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)

Also you can do <,>,>=,<= etc

你也可以做 <,>,>=,<= 等