Home > database >  Add a day to an input of type datetime-local
Add a day to an input of type datetime-local

Time:12-29

Best regards I have a question since what I am trying to do is add one more day to an input that is of the datetime-local type than and I try with JQuery but it only works for me if the input is of the date type which I would like to know how doing it works for me with datetime-local This is the code I take as a reference that works with date:

$('#checkInDate')[0].valueAsDate = new Date();

    $('#checkInDate').change(function() {
    var date = this.valueAsDate;
    date.setDate(date.getDate()   1);
    $('#checkOutDate')[0].valueAsDate = date;
    });

    $('#checkInDate').change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Date Ini:  <input type="date" id="checkInDate">
Date Out: <input type="date" id="checkOutDate"> <br>

CodePudding user response:

The datetime-local input doesn't have a valueAsDate property. But you can use valueAsNumber instead.

So whenever you set the value, cast the date object to a number with input.valueAsNumber = date, and whenever you retrieve the value, cast it to a date with new Date(input.valueAsNumber)

Also, for setting the initial value of the date, to limit the precision to minutes you can do Math.floor(Date.now() / 6e4) * 6e4, and to account for the timezone, you can subtract the timezone offset.

$('#checkInDate')[0].valueAsNumber = 6e4 * (Math.floor(Date.now() / 6e4) - new Date().getTimezoneOffset());

$('#checkInDate').change(function() {
  var date = new Date(this.valueAsNumber);
  date.setDate(date.getDate()   1);
  $('#checkOutDate')[0].valueAsNumber =  date;
  
  console.log(new Date(this.value)) // retrieving as data
});

$('#checkInDate').change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Date Ini:  <input type="datetime-local" id="checkInDate">
Date Out: <input type="datetime-local" id="checkOutDate"> <br>

Of course, when retrieving the data to use in the backend or store in a DB, make sure to construct the date object from this.value instead of this.valueAsNumber.

  • Related