Javascript日期验证对今天的日期不起作用

javascript date validation is not working for today date

本文关键字:日期 不起作用 今天 验证 Javascript      更新时间:2023-09-26

我已经得到下面的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();
}

当我给出未来的日期时,它工作得很好,但它不能为今天的日期工作。我还需要查一下今天的日期。当我尝试输入今天的日期时,我无法找出错误警报。

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

把Date对象看作时间戳。它基于unix风格的时间戳(从1970年1月1日开始的秒数),所以Date对象不是日期,而是Date和Time。

你比较的也是时间,这可能会有点不确定。如果只有几天,试着使用:

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
}

您正在毫秒级别上将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;
}