Set restriction for the datetime-local , only selecting the current date

Viewed 930

I am now writing a form that will include the date picker .. and I'm trying to use the element. for now, I would like to restrict it to only select the current date.

for example today is July 7

so the selection on the date picker will be only July 7

Can someone help me with it? I'm new at web application

<div class="form-group ">
  <label class="font-weight-bold">Check in</label>
  <input type="datetime-local" id="datefield">
</div>
<div class="form-group ">
  <label class="font-weight-bold">Check Out</label>
  <input type="datetime-local" id="CheckOut">
</div>

1 Answers

<div class="form-group ">
  <label class="font-weight-bold">Check in</label>
  <input type="datetime-local" id="CheckIn" min="2021-07-07T00:00" max="2021-07-07T23:59" >
</div>
<div class="form-group ">
  <label class="font-weight-bold">Check Out</label>
  <input type="datetime-local" id="CheckOut" min="2021-07-07T00:00" max="2021-07-07T23:59">
</div>

OR, if you want it for "the current day" you will need some Javascript:

const today=(new Date()).toLocaleString("EN-CA").slice(0,10); // get local current date
document.querySelectorAll('input[type="datetime-local"]').forEach(el=>{
 el.min=today+"T00:00"; el.max=today+"T23:59";
})
<div class="form-group ">
  <label class="font-weight-bold">Check in</label>
  <input type="datetime-local" id="CheckIn">
</div>
<div class="form-group ">
  <label class="font-weight-bold">Check Out</label>
  <input type="datetime-local" id="CheckOut">
</div>

I am using Date.prototype.toLocaleString() here instead of Date.prototype.toISOString() as this will return the locale date and not the GMT date, which might differ at certain times of the day, depending on which time zone the user is in. The locale "EN-CA" ensures the "YYYY-MM-DD" format.

Related