tweaktweak tweaktweak - 8 days ago 5
HTML Question

How to compare two dates from input?

there are two inputs

From: <input id="from" type="date" placeholder="dd/mm/yy"><br>
To: <input id="to" type="date" placeholder="dd/mm/yy">


I wanna compare these two inputs so as to ensure that the check out date is no earlier than the check in date. But how to compare? thx

Answer

You can get the value of your inputs by using javascript:

var fromValue = document.getElementById('from').value;
var toValue = document.getElementById('to').value;

then use the javascript date object to convert them to dates:

var fromDate = new Date(fromValue);
var toDate = new Date(toValue);

and remove time since midnight:

fromDate.setHours(0,0,0,0);
toDate.setHours(0,0,0,0);

then compare fromDate to toDate:

if (fromDate === toDate) { ... }
Comments