2021-07-25设计方法,计算两个日期之间相差多少天。两个日期的年月日由参数控制。

class Datecount {
    public static void main(String[] args) {
        int value = 0;
        int value1 = 0, value2 = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个年份:");
        int year = scanner.nextInt();
        System.out.println("请输入一个月份:");
        int month = scanner.nextInt();
        System.out.println("请输入一个天数:");
        int day = scanner.nextInt();
        System.out.println("请输入另一个年份:");
        int year0 = scanner.nextInt();
        System.out.println("请输入另一个月份:");
        int month0 = scanner.nextInt();
        System.out.println("请输入另一个天数:");
        int day0 = scanner.nextInt();
        value1 = getday(year, month, day);
        value2 = getday(year0, month0, day0);
        value = Math.abs(value1 - value2);
        if (value == 0)
            System.out.println("请重新输入!");
        else
            System.out.println("日期相差" + value + "天");
    }

    public static int getday(int year, int month, int day) {
        int yearcount = 0, monthcount = 0, yearday = 0, monthday = 0;
        if (year > 1) {
            for (int n = 1; n < year; n++) {
                if ( n%4==0 && n%100!=0 || n%400==0 )
                    yearcount = 366;
                else
                    yearcount = 365;
                yearday += yearcount;
            }
           if (month >= 1 && month <= 12) {
                for (int i = 1; i < month; i++) {
                    if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
                        monthcount = 31;
                    else if (i == 2 && yearcount == 365)
                        monthcount = 28;
                    else if (i == 2 && yearcount == 366)
                        monthcount = 29;
                    else
                        monthcount = 30;
                    monthday += monthcount;
                }
                if (day >= 1 && day <= 31) {
                    return yearday + monthday + day;
                } else {
                    System.out.println("天数输入有误!");
                    return 0;
                }
            }
            else {
                System.out.println("月份输入有误!");
                return 0;
            }
        }
        else{
            System.out.println("年份输入有误!");
            return 0;
        }
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值