jQuery Datepicker day count
I've got two jQuer开发者_StackOverflow中文版y UI datepickers and when they've both had dates chosen, I'd like the difference between these dates to be displayed in a separate input[type="text"]
as soon as the second date is selected.
Also, I'd ideally like my count to subtract any weekend days and just count days from Monday - Friday.
My (relevant) code is as follows:
JS:
$('#firstday, #lastday').datepicker({
dateFormat: 'dd/mm/yy'
});
XHTML:
<label for="firstday">First Day of Leave</label>
<input type="text" name="firstday" id="firstday" />
<label for="lastday">Last Day of Leave</label>
<input type="text" name="lastday" id="lastday" />
<label for="totaldays">Total Days</label>
<input type="text" name="totaldays" id="totaldays" />
Lots of searching has led me to lots of different solutions, none of which I can get to work as I'd like so any ideas would be appreciated.
Something like this should work:
$("#firstday, #lastday").datepicker({
onSelect: function (){
// Date will give time difference in miliseconds, that is why we divide with 1000*60*60*24
var firstday = new Date($("#firstday").val().split("/").reverse().join(","));
var lastday = new Date($("#lastday").val().split("/").reverse().join(",");
$("#totaldays").val((lastday - firstday) / 86400000);
}
});
In node console it gives:
> x = new Date("18/5/2010".split("/").reverse().join(","))
Mon, 17 May 2010 22:00:00 GMT
> y = new Date("18/5/2015".split("/").reverse().join(","))
Sun, 17 May 2015 22:00:00 GMT
> x-y
-157766400000
> y-x
157766400000
> (y-x)/86400000
1826
-- EDIT --
When you have starting date and ending date number of days that are weekend is easily calculated using getDay() which returns from 0 for Sunday, 1 for Monday ... 6 for Saturday.
Yo could use .getMonth() and .getDate() combined with few else{} conditions for holidays as well.
var weekend_count = 0;
for (i = firstday.valueOf(); i <= lastday.valueOf(); i+= 86400000){
var temp = new Date(i);
if (temp.getDay() == 0 || temp.getDay() == 6) {
weekend_count++;
}
}
and in the end you just do
$("#totaldays").val( (lastday - firstday) / 86400000 - weekend_count);
Just to make a note at the end. You should probably extrapolate this code (as much of it as you can) in a separate function in order to keep your code easier to maintain and in case you need that same function on some other place.
Good luck.
精彩评论