问题
In this JavaScript I am able to calculate the difference two dates but am not able to find the Sunday between dates. If Sunday occurs between two dates then subtract the Sunday from the dates and display the total number of days.
$(function () {
$(".datepicker").datepicker({ dateFormat: 'dd M y'});
$(".datepicker_2").datepicker({ dateFormat: 'dd M y'});
$('.datepicker').change(function () {
var start = $.datepicker.parseDate('dd M y', $(".datepicker").val());
var end = $.datepicker.parseDate('dd M y', $(".datepicker_2").val());
var total = 1;
if (start > end && end != null) {
alert("Begin date must be before End date");
$('.txtnoofdays').val(null);
startdate.focus();
}
if (end != null) {
var days = ((end - start) / 1000 / 60 / 60 / 24) + total;
$('.txtnoofdays').val(parseInt(days));
}
});
$('.datepicker_2').change(function () {
var start = $.datepicker.parseDate('dd M y', $(".datepicker").val());
var end = $.datepicker.parseDate('dd M y', $(".datepicker_2").val());
var total = 1;
if (start > end) {
alert("Begin date must be before End date");
$('.txtnoofdays').val(null);
startdate.focus();
}
var days = ((end - start) / 1000 / 60 / 60 / 24) + total;
$('.txtnoofdays').val(parseInt(days));
});
});
回答1:
You should use the Javascript Date Object and more especially the getDay() method.
Then you can increment your start
date until end
date and count the Sundays you encounter, something like :
var start = $.datepicker.parseDate('dd M y', $(".datepicker").val());
var end = $.datepicker.parseDate('dd M y', $(".datepicker_2").val());
var startDate = new Date(start);
var endDate = new Date(end);
var totalSundays = 0;
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 0){
totalSundays++;
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalSundays);
Nota Bene :
I did not understand your "substraction rule"
来源:https://stackoverflow.com/questions/26629860/find-the-number-of-sunday-between-two-dates-and-if-sunday-comes-between-two-date