Date Differentiator
It calculates the difference in the 2 given dates
by Abhishek Kumar
HTML
<table>
<tr>
<td>From Date:</td>
<td>
<input type="date" id="ifd_fromdate">
</td>
</tr>
<tr>
<td>To Date:</td>
<td>
<input type="date" id="ifd_todate">
</td>
</tr>
<tr>
<td colspan="2">
<button id="btn_submit">Submit</button>
</td>
</tr>
<tr>
<td colspan="2" class="output"><b>Difference</b>
<ul id="spn_datediff"></ul>
</td>
</tr>
</table>
CSS
table button,
table input {
font-size: 14px;
font-family: Calibri;
}
table button {
padding: 10px 10px 10px 10px;
width: 100px;
margin-top: 10px;
}
table input {
padding: 5px 10px 5px 10px;
}
table td {
font-family: Calibri
}
table td.output {
padding-top: 15px;
}
JavaScript
var ifd_fromdate = document.getElementById('ifd_fromdate');
var ifd_todate = document.getElementById('ifd_todate');
var btn_submit = document.getElementById('btn_submit');
var spn_datediff = document.getElementById('spn_datediff');
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
function dateDiffInDays(a, b) {
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
var utc = Math.floor((utc2 - utc1) / _MS_PER_DAY);
return utc;
}
function getAge(days) {
var y = Math.floor(days / 365);
var m = Math.floor((days % 365) / 30);
var d = Math.floor((days % 365) % 30);
return y + "y " + m + "m " + d + "d";
}
btn_submit.addEventListener('click', function() {
var fromdate = ifd_fromdate.value;
var todate = ifd_todate.value;
var diff = dateDiffInDays(new Date(fromdate), new Date(todate));
var diffs = [
getAge(diff),
(diff / 365).toFixed(2) + " years",
(diff / 30).toFixed(2) + " months",
diff + " days",
(diff / 7).toFixed(2) + " weeks",
(diff * 24) + " hours",
(diff * 24 * 60) + " minutes",
(diff * 24 * 60 * 60) + " seconds",
];
spn_datediff.innerHTML = "<li>" + (diffs).join("</li><li>") + "</li>";
});