【问题标题】:javascript date validation is not working for today datejavascript 日期验证不适用于今天的日期
【发布时间】:2014-08-14 06:54:16
【问题描述】:

我有下面的 java 脚本代码,它将验证日期范围......当用户输入今天或任何未来日期时,我将 IsValid 设置为 true,然后将执行保存操作......

为此我写了下面的代码..

 function Save(e) {
    var popupNotification = $("#popupNotification").data("kendoNotification");

    var container = e.container;
    var model = e.model;

    var isValid = true;
    var compareDate = e.model.DeliveryDate;
    alert(compareDate);
    var todayDate = new Date();
    var compareDateModified = new Date(compareDate)
    alert(compareDateModified);
    if (compareDateModified > todayDate || compareDateModified === todayDate) {
        isValid = true;

    }
    else
        isValid = false;
    e.preventDefault();
    if (isValid == false)
    {

        popupNotification.show("Delivery Date should be today date or Greater", "error");

    }
    $('#Previous').show();
    $('#Next').show();
}

当我给出未来的日期时它工作正常,但它不适用于今天的日期。我还需要检查今天的日期。当我尝试输入今天的日期时,我无法弄清楚错误警报。

【问题讨论】:

    标签: javascript jquery validation date datetime


    【解决方案1】:

    您正在将 compareDateModified 与 todayDate 进行毫秒级别的比较。在日级别进行比较:

    var todayDate = new Date();
    todayDate.setHours(0,0,0,0);
    //you may also have to truncate the compareDateModified to the first
    //second of the day depending on how you setup compareDate
    if (compareDateModified >= todayDate) {
        isValid = true;
    }
    

    【讨论】:

      【解决方案2】:

      您正在比较两个相同类型但不同的对象,因此总是会导致“不相等” 如果您使用 date.getTime() ,您将在比较中获得更好的结果 - 但前提是时间组件当然是相同的。

      【讨论】:

        【解决方案3】:

        把 Date 对象想象成一个时间戳。它基于 unix 样式的时间戳(自 1970 年 1 月 1 日以来的秒数),因此 Date 对象不是日期,而是日期和时间。

        您还要比较的是时间,这可能有点不确定。如果只有几天很重要,请尝试使用:

        fullCompareDate = compareDateModified.getFullYear() + "/" + compareDateModified.getMonth() + "/" + compareDateModified.getDate();
        fullTodayDate= todayDate.getFullYear() + "/" + todayDate.getMonth() + "/" + todayDate.getDate();
        if(compareDateModified>todayDate||fullCompareDate==fullTodayDate)
        {
          //Do something
        }
        

        这将比较日期和时间以确保它们更大或检查当前日期与比较日期(作为字符串)

        另一种解决方案是将两个日期的时间都去掉:

        compareDateModified.setHours(0,0,0,0);
        todayDate.setHours(0,0,0,0);
        if(compareDateModified>=todayDate)
        {
          //Do something
        }
        

        【讨论】:

          猜你喜欢
          • 2016-07-07
          • 1970-01-01
          • 1970-01-01
          • 2016-02-20
          • 2014-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-28
          相关资源
          最近更新 更多