How to make the <input type="datetime-local" > have the maximum date and time value, today. Through JS.

It is necessary that when choosing the date and time of the user, there should be a limit to today and the time of opening the modal window.

  • The question is not clear. Please open your mind. - Stepan Kasyanenko 1:46 pm
  • When selecting the date and time of the user, it is necessary to have a restriction until today and a modal window opening time. That is, a modal window opens and there is a choice of date and time. - WINDRIA 1:49 pm

2 answers 2

Purely for date, use date :

 var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; // Месяца идут с 0, так что добавляем 1. var yyyy = today.getFullYear(); if(dd < 10){ dd='0' + dd } if(mm < 10){ mm='0' + mm } today = yyyy + '-' + mm + '-' + dd; document.getElementById("datetime-local").setAttribute("max", today); 
 <input id="datetime-local" type="date"></input> 

If you need more time, then you can like this:

 var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; // Месяца идут с 0, так что добавляем 1. var yyyy = today.getFullYear(); var minutes = today.getMinutes(); var hour = today.getHours(); if(dd < 10){ dd='0' + dd } if(mm < 10){ mm='0' + mm } if(hour < 10){ hour='0' + hour } if(minutes < 10){ minutes='0' + minutes } today = yyyy + '-' + mm + '-' + dd + 'T' + hour + ':' + minutes; document.getElementById("datetime-local").setAttribute("max", today); 
 <input id="datetime-local" type="datetime-local"></input> 

  • This only works if you click with the mouse. Manually from the keyboard, you can drive any date. - humster_spb
  • I agree, then I would put the package to work with datetime, but here the author needs to clarify what exactly he needs. - Yaroslav Molchan
  • So that there is a restriction like in your code, only with the addition of time, or will it be easier to use this and add a new time field next to it? - WINDRIA
  • @WINDRIA added a code to the response where and there is a time check, but it's still better to check the server. - Yaroslav Molchan 2:12 pm
 <input type="datetime-local" id="meeting-time" name="meeting-time" value="2018-06-12T19:30" min="2018-06-07T00:00" max="2018-06-14T00:00"> 
  1. value - the format that you set as the base value
  2. min - the minimum date
  3. max - the maximum date that can be set by the user

    link to more information:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

  • Automatic date limitation needed - WINDRIA pm