找出两个日期之间的星期天数,如果星期日在两个日期之间,则减去该星期天 [英] Find the number of sunday between two dates and if sunday comes between two dates then substract the sunday

查看:57
本文介绍了找出两个日期之间的星期天数,如果星期日在两个日期之间,则减去该星期天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此JavaScript中,我能够计算两个日期之间的差额,但无法找到两个日期之间的星期日.如果星期日发生在两个日期之间,则从日期中减去星期日,然后显示总天数.

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));

    });

});

推荐答案

您应该使用Javascript日期对象,尤其是 getDay()方法.

You should use the Javascript Date Object and more especially the getDay() method.

然后,您可以增加您的开始日期,直到 end 日期,并计算遇到的星期日,例如:

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:

Nota Bene :

我不明白您的减法规则"

I did not understand your "substraction rule"

这篇关于找出两个日期之间的星期天数,如果星期日在两个日期之间,则减去该星期天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆