Lachlanf Lachlanf - 3 months ago 17
HTML Question

Add one day to date string in javascript

I am setting the min of

checkOut
as the value of
checkIn
. My problem comes that i need to add one day to
firstdate
. (Should not be able to check out on or before the check in day.)

<script>
function updatedate() {
var firstdate = document.getElementById("checkIn").value;
document.getElementById("checkOut").value = "";
document.getElementById("checkOut").setAttribute("min",firstdate);
}
</script>

Check In
<input type="date" id="checkIn" onchange="updatedate();" name="checkin">

Check out
<input type="date" id="checkOut" min="" name="checkout">

Answer

It's sort of do-able but it only works in Chrome since that's the only browser that supports a date input at the moment. Oh, and this solution uses momentjs because parsing a date and correctly adding 1 day to it is way harder that it sounds.

function updatedate() {
  var checkin = document.getElementById("checkIn").value;
  checkin = moment(checkin);
  var checkout = checkin.add(1, 'd');
  document.getElementById("checkOut").setAttribute("min", checkout.format('YYYY-MM-DD'));
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div class="container">
  Check In
  <input type="date" id="checkIn" onchange="updatedate();" name="checkin">Check out
  <input type="date" id="checkOut" min="" name="checkout">
</div>

Comments