Skip to content Skip to sidebar Skip to footer

Date Should Not Be Older Than 1 Year From Current Date (Today's Date) In Javascript

I have a requirement where I need to find the date entered in the textfield should not be older than 1 year from current date. I have coded for the former one but for the latter re

Solution 1:

check it out here:

https://jsfiddle.net/v63u7ksf/

    var yearAgoTime = new Date().setFullYear(currentTime.getFullYear()-1);


    var compDate2 = enDate - yearAgoTime;
    if (compDate2<0)
    {
        errorMsg="More than 1 year ago not allowed.";
    }

Solution 2:

You can check diff yourself as suggested by others, however, I would suggest you to use moment.js for date time processing. Its very handy.


Solution 3:

try this, after getting the string from the input, you can call a function as,

function dateDiff(entereddate) {
  one_year_next_date = new Date(new Date().setYear(new Date().getFullYear() + 1))
  entereddate = new Date(entereddate);
  return (one_year_next_date.getTime() - entereddate.getTime()) / 1000 / 60 / 60 / 24 // diff in days
}

var netWorthFlag = $("#NetworthDate").val();

date_difference = dateDiff(netWorthFlag); /* your input entered date */
/* eg: dateDiff("02/16/2015");  */(check date format ("02/16/2015"))

This returns the difference in the dates as number of days.

Then you can write your condition,

if(date_difference > 365(/* 366 */))
  /**** You can even check the leap year of entered date, or next years date ****/
  {
    /**** do your stuff ****/
  } 
else
  {
    /**** do your stuff ****/
  }

You can even check the leap year here, taking the year from that date.(check date format ("02/16/2015"))


Post a Comment for "Date Should Not Be Older Than 1 Year From Current Date (Today's Date) In Javascript"