java计算两个日期的天数差


public class betweendate {


    public int isLeapYear(int year)
    {
        return (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0) ? 1 : 0;
    }


    public int getDaySub(int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay)
    {

        int totalDay = 0;


            for (int i = 0; i <= (endYear - startYear); i++)
            {

                if (i == 0) // 第一年
                {
                    for (int j = startMonth; j < 13; j++) {
                        int month = j;
                        int days = getMonthDays(startYear, month);
                        // 第一年的开始月份
                        if (j == startMonth)
                        {
                            days = getMonthDays(startYear, month) - startDay;//得到开始那个月的剩余天数
                        }
                        totalDay += days;
                    }

                }



                else if (i == (endYear - startYear)) // 最后一年
                {
                    for (int j = 1; j <= endMonth; j++) {
                        int month = j;
                        int eDay = getMonthDays(endYear, month);
                        // 结束日期的最后一天小于最后一月的天数
                        if (j == endMonth && endDay < eDay) {
                            eDay = endDay;
                        }
                        totalDay += eDay;
                    }
                    // 中间年
                }

                else {

                    int year = startYear + i;

                    totalDay += (365+isLeapYear(year));


                }
            }

        return totalDay;
    }




    public int getMonthDays(int year, int month) //判断本月多少天
    {
        if (month == 2) 
        {
            return isLeapYear(year)+28;
        }
        else if (month == 4 || month == 6 || month == 9 || month == 11)
        {
            return 30;
        }
        else {
            return 31;
        }
    }




    public static void main(String[] args) {
        betweendate t = new betweendate();
        int r = t.getDaySub(1999, 3, 12, 2021, 10, 20);
        System.out.println(r);
    }



}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值