我正在使用JavaScript计算两天之间的日差。在某些情况下,我得到了正确的结果,但有些情况下我无法得到正确的结果。我在下面解释我的代码。
function caldate(){
var difference=Math.abs((parseInt(document.getElementById('dayto').value)%7)-(parseInt(document.getElementById('dayfrom').value)%7))+1;
alert(difference);
}
当day to
是星期天时,我得到了错误的结果。我的plunkr code就在这里。我需要计算两天之间的差异,包括选定的两天。
答案 0 :(得分:2)
不要使用%
?
function caldate() {
var day1 = document.getElementById('dayfrom').value;
var day2 = document.getElementById('dayto').value;
var difference = Math.abs((parseInt(document.getElementById('dayto').value)) - (parseInt(document.getElementById('dayfrom').value))) + 1;
if (isNaN(difference)) {
return true;
}
document.getElementById("output").innerHTML = "<p>Difference between day " +
day1 + " and day " +
day2 + " is: " +
difference + " day" +
(difference > 1 ? "s" : '') +
"</p>" +
document.getElementById("output").innerHTML
}
&#13;
<h1>Hello</h1>
<div class="col-md-6">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Day From :</span>
<select id="dayfrom">
<option value="">Select day</option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wedensday</option>
<option value="4">Thrusday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Day To :</span>
<select id="dayto">
<option value="">Select day</option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wedensday</option>
<option value="4">Thrusday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
</div>
</div>
<input type="button" id="btn" onclick="caldate();" value="Check">
<div id="output"></div>
&#13;