简体   繁体   中英

How can I check that a date is not in the past without including the current day?

So I have a checkDate() function that I use to verify the date entered on a web form is not in the past before submitting. The problem is, this function also returns an error if the date entered is today's date. I'm assuming this has something to do with how datetimes are formatted as DD:MM:YYYY HH:MM:SS.sss and then converted to their epoch value, but I'm not sure how to go about validating that the entered date is NOT today while still checking that it's not a past date.

I've posted my checkDate() function in its entirety below:

Please note: the textbox with the date string we are checking against is named txtNeededBy .

function checkDate() {

    var date = new Date($("#txtNeededBy").val());
    ValidateDate = false;

    if (Date.parse(date) < Date.now()) {
        sb.append("<li>Needed by date must not be in the past.</li>");
        $("#txtNeededBy").addClass("input_error");
        ValidateDate = true;
        if (sb.toString().length > 0) {
            $(".Errors").html(sb.toString());
            $(".Errors").show();
            return false;
        }
    } else {
        $("#txtNeededBy").removeClass("input_error");
    }

    if (ValidateDate === true) {
        return false;
    }
}

I would strongly recommend using a library like Date.js

That library has an .is() method that allows you to do these sorts of comparisons extremely easily. Don't reinvent the wheel :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM