Date Difference
HTML
<script src="https://rawgithub.com/timrwood/moment/2.1.0/min/moment.min.js"></script>
<div class="wrap">
<input type="text" id="appointment" placeholder="Appointment Date" />
<br />
<input type="text" id="birthdate" placeholder="Date of Birth" />
<br />
<input type="submit" id="submit" />
</div>
<div id="result" class="wrap">Valid/Invalid</div>
<div id="result1" class="wrap">dvDate</div>
<div id="result2" class="wrap">curDate</div>
<div id="result3" class="wrap">dvDate - curDate</div>
<div id="note">
<p>This is using the Moment.JS library.</p>
</div>
CSS
* {
margin: 0;
padding: 0;
}
body {
width: 95%;
padding: 2.5%;
}
.wrap {
padding: 1em;
border-radius: 6px;
background: #eee;
}
#result {
margin: 1em 0 0 0;
text-align: center;
}
#note {
width: 100%;
text-align: center;
position: absolute;
bottom: 5px;
display: block
}
JavaScript
// Counts Months - Disregards Days
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
$('#submit').on('click', function() {
var month = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var b;
var yyyy = 2016;
var curVal = "01DEC";
var dvVal = "01APR";
var dd = dvVal.substr(0, 2);
var mm = dvVal.substr(2, 3);
var dd1 = curVal.substr(0, 2);
var mm1 = curVal.substr(2, 3);
var d = new Date();
var dvDate = new Date(yyyy, month.indexOf(mm.toUpperCase()), dd);
var curDate = new Date(yyyy, month.indexOf(mm1.toUpperCase()), dd1);
var timeDiff = dvDate.getTime() - curDate.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if(diffDays > 120)
{
dvDate = new Date(yyyy-1, month.indexOf(mm.toUpperCase()), dd);
}
if(diffDays < -240)
{
dvDate = new Date(yyyy+1, month.indexOf(mm.toUpperCase()), dd);
}
if (dvDate < curDate)
{
b = false;
}
else
{
b = true;
}
$('#result1').text(dvDate);
$('#result2').text(curDate);
$('#result3').text(diffDays);
$('#result').text(b);
});