javascript date validation to check whether it exceeds exactly next year's date

1.4k views Asked by At

I have a requirement where i need to find the date entered in the textfield should not be less than currentdate and future date should not exceed exactly date after 1 year from the eentered date.I have coded for former one but i later requirement i could not do it. I have posted code for checking less than current date here. Please let me know for checking if the date entered exceed the date after 1 year.

var currentDate = new Date();
var nextDate = new Date();

function checkLessThanCurrentDate() {
    //var dateEntered = arguments[0]; -->Will have date that come form textfield
    var day = dateEntered.split("/")[0];
    var month = dateEntered.split("/")[1];
    var year = dateEntered.split("/")[2];
    //--->Logic for chekcing date less than current date
    if ((year < currentDate.getFullYear() || (month - 1 < currentDate.getMonth() &&
    year <= currentDate.getFullYear()) || ((day < currentDate.getDate()) && (month -
    1 <= currentDate.getMonth()) &&
    (year <= currentDate.getFullYear())))) {
        return true;
    }

    else {
        return false;
    }
}
3

There are 3 answers

1
Konstantin Dinev On BEST ANSWER

Here's how to get the date one year from now:

var now = new Date();
var oneYear = new Date();
var oneYear.setYear(now.getFullYear() + 1);

if (dateEntered > oneYear) {
    // logic
}
0
B Wells On

I think this should work for both your requirements:

function isValidDate(dateToCheck)
{
    return isLessThanYearFromToday(dateToCheck) && dateToCheck >= new Date();
}

function isLessThanYearFromToday(dateToCheck)
{
    var yearFromToday = new Date();
    yearFromToday.setFullYear(yearFromToday.Year + 1);
    return dateToCheck <= yearFromToday;
}
0
ozil On

you need to use .getTime() method. .getTime() return the time in millisonds

var toDayDate = new Date();
var enteredDate = new Date('06/09/2015');      // mm/dd/yyyy formate

if(toDayDate.getTime()<enteredDate.getTime() && toDayDate.getTime()+(365*24*60*60*1000) > enteredDate.getTime()){
    alert();
}  

DEMO