简体   繁体   中英

How to get proper difference value between two days using JavaScript

I am calculating the day difference between two day using JavaScript. For some cases I am getting right result but some cases I cannot get the right result. My code is below:

function caldate(){
       var difference=Math.abs((parseInt(document.getElementById('dayto').value)%7)-(parseInt(document.getElementById('dayfrom').value)%7))+1;
           alert(difference);
}

Here when day to is Sunday I am getting the wrong result. My plunkr code is here. I need to calculate the difference between two day including both selected days.

Don't use % ?

 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 }
 <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM