Find the number of sunday between two dates and if sunday comes between two dates then substract the sunday

£可爱£侵袭症+ 提交于 2021-02-11 12:23:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!