计算日期相差的天数

大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210。后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记上标注着:5343,因此可算出那天是:1791年12月15日。高斯获得博士学位的那天日记上标着:8113 请你算出高斯获得博士学位的年月日。


package com.test;
public class MainTest {
         
    public static void main(String[] args) {
        calculate(8113);
    }
         
    static int[] month1 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    static int[] month2 = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //闰年
         
    //判断是否为闰年
    public static boolean isLeapYear(int year) {
        if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
            return true;
        } else {
            return false;
        }
    }
         
    public static void calculate(int total) {
        int y = 0;
        int m = 0;
        int d = 0;
        int sum1 = 0;
        int sy = 1777;
             
        //计算1777年高斯出生了总共多少天
        if(isLeapYear(1777)) {
            for(int i = 4; i < 12; i++) {
                sum1 += month2[i];
            }
            sum1 += month2[3] - 30 + 1;
        } else {
            for(int i = 4; i < 12; i++) {
                sum1 += month1[i];
            }
            sum1 += month2[3] - 30 + 1;
        }
             
        //计算出生total天是哪一年
        while(sum1 < total) {
            sy++;
            if(isLeapYear(sy)) {
                sum1 += 366;
            } else {
                sum1 += 365;
            }
                 
        }
        y = sy;
             
        //计算出月份
        if(isLeapYear(sy)) { //闰年
            sum1 -= 366;
            int i = 0;
            for(;i < 12; i++) {
                sum1 += month2[i];
                if(sum1 > total) {
                    break;
                }
            }
            m = i+1;//计算月份,因为月份是从0计算的,所以显示时需要加1
            sum1 -= month2[i];
            d = total - sum1;//计算天数
        } else { //平年
            sum1 -= 365;
            int i = 0;
            for(;i < 12; i++) {
                sum1 += month1[i];
                if(sum1 > total) {
                    break;
                }
            }
            m = i+1;
            sum1 -= month2[i];
            d = total - sum1;
        }
        System.out.println(y + "-" + m + "-" + d);
    }
         
         
}

答案:1799-7-16

你可能感兴趣的:(闰年,日期相差天数)