【问题标题】:how to compare current date to a future date and validate it in javascript如何将当前日期与未来日期进行比较并在 javascript 中进行验证
【发布时间】:2015-12-03 16:02:17
【问题描述】:

`

`

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

下面是我要添加函数的表单。

【问题讨论】:

标签: javascript validation date


【解决方案1】:

如果你使用过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>

【讨论】:

  • 感谢您的帮助。下面是我希望添加该脚本的代码。你能帮我用我里面的值修改它吗
【解决方案2】:

如果您的日期是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;
 }

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

【讨论】:

    【解决方案3】:

    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)

    你也可以做 ,>=,

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多