Skip to content Skip to sidebar Skip to footer

How Can I Use Input Type Date To Dynamically Only Allow For One Year From Current Date?

Here is my code so far. I am not sure how to accomplish a max date other than setting that in the input tag itself. I want it to be dynamic so whatever the current date is, the cal

Solution 1:

Setting the min and max values for a date input based on today's date can be done when the page loads:

// Formt date as YYYY-MM-DDfunctionformatISOLocal(d) {
  letz = n => ('0' + n).slice(-2);
  return d.getFullYear()+'-'+z(d.getMonth()+1) + '-' + z(d.getDate());
}

window.onload = function() {
  let inp = document.querySelector('#i0');
  let d = newDate();
  inp.min = formatISOLocal(d);
  inp.defaultValue = inp.min;
  d.setFullYear(d.getFullYear() + 1);
  inp.max = formatISOLocal(d);
  // Debugconsole.log(inp.outerHTML);
}
<inputtype="date"id="i0">

If the user agent doesn't support input type date, this will still set the min/max/default values, but you'll have to handle out of range values yourself.

Solution 2:

Just add a year to the current date

var dtToday = newDate();
dtToday.setYear(dtToday.getYear() + 1);

Solution 3:

$(function(){
  var dtToday = newDate();
  dtToday.setFullYear(dtToday.getFullYear() + 1)
  let formatted_date = dtToday.getFullYear() + "-" + (dtToday.getMonth() + 1) + "-" + dtToday.getDate()
  alert(formatted_date);
  $('#txtDate').attr('max', formatted_date);
});

Solution 4:

You can't add to a date object like that; you need to first get it as a timestamp. You can do that by using Date.now() or, if you need the Date object, dtToday.getTime().

That gives you a timestamp in milliseconds, so you also need to convert 365 days into milliseconds; meaning you want to add 365 * 24 * 60 * 60 * 1000 to it, not just 365.

Post a Comment for "How Can I Use Input Type Date To Dynamically Only Allow For One Year From Current Date?"