0

In my form, I only want the date entered to be either today or the future. The function I'm using only accepts the future, and I can't figure out why?

//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;
}

A separate function calling on a RegEx and the above function:

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 code for Date Input:

<input type="text" id="date" placeholder="DD/MM/YYYY" onkeyup="checkDate()">
Zong
  • 6,160
  • 5
  • 32
  • 46
RoyalSwish
  • 1,503
  • 10
  • 31
  • 57
  • possible duplicate of [Comparing date part only without comparing time in javascript](http://stackoverflow.com/questions/2698725/comparing-date-part-only-without-comparing-time-in-javascript) – epascarello Feb 03 '14 at 17:18

2 Answers2

1

Try normalising the dates

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();
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

Because the current time has hours/minutes/seconds/milliseconds and the time entered by the string is based off of midnight.

epascarello
  • 204,599
  • 20
  • 195
  • 236