功能只接受未来的日期,想要未来和当前?

时间:2014-02-03 17:11:50

标签: javascript regex

在我的表格中,我只希望输入的日期为今天或未来。我正在使用的功能只接受未来,我无法弄清楚为什么?

//This function checks whether the input date is today or the future

function isFutureDate(idate) {
    var today = new Date().getTime(),
        idate = idate.split("/");

    idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
    return (idate - today) >= 0 ? true : false;
}

一个单独的函数调用RegEx和上面的函数:

function checkDate() {
    var redate = /((0)[1-9]|(1)[0-9]|(2)[0-9]|(3)[0-1])[\/](0[1-9]|1[012])[\/](20)(1)[4-7]/;
    var valid = true;
    var idate = document.getElementById("date");

    if (redate.test(idate.value)) {
        if (isFutureDate(idate.value)) {
            idate.style.border = "1px inset #EBE9ED";
            idate.style.borderRadius = "2px";
            document.getElementById("datewarn").style.display = "none";
        } else {
            idate.style.border = "1px solid red";
            idate.style.borderRadius = "2px";
            document.getElementById("datewarn").style.display = "none";
        }
    } else {
        idate.style.border = "1px solid red";
        document.getElementById("datewarn").innerHTML = "Enter a date in the format DD/MM/YYYY.";
        idate.title = "Please enter a date in the format DD/MM/YYYY.";
        document.getElementById("datewarn").style.display = "block";
        valid = false;
    }
}

日期输入的HTML代码:

<input type="text" id="date" placeholder="DD/MM/YYYY" onkeyup="checkDate()">

2 个答案:

答案 0 :(得分:1)

尝试规范化日期

function isFutureDate(idate) {
  var today = new Date(), idateParts = idate.split("/");
  today.setHours(12,0,0,0); // or 0,0,0,0 depending on preference
  idate = new Date(idateParts[2], idateParts[1] - 1, idateParts[0],12,0,0,0).getTime();

答案 1 :(得分:0)

因为当前时间有小时/分钟/秒/毫秒,而字符串输入的时间是基于午夜。