计算给定日期后N天的日期

/**
 * 
 */

/**
 * 计数给定日期后N天的日期
 * 
 * @author
 *
 */
public class T0712 {
    public static int year = 2009;
    public static int month = 12;
    public static int day = 31;
    // days代表N天后的N
    public static int days = 366;
    // 统计跨年的个数
    public static int years;
    // 年份数组
    public static int a[] = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    public static void main(String[] args) {
        
        if (!isLeapYear(year) && month <= 2) {
            days = days + 1;
        }
        
        // 判断是否跨越当前指定月
        if (day + days > a[month]) {
            // 月份循环计数
            int i;
            // days减去当前给定月份剩余的天数
            days = days - (a[month] - day);
            System.out.println(days);

            // 逐月减去天数,i统计月份
            for (i = month + 1; i <= 12; i++) {
                if (days > a[i]) {
                    days = days - a[i];
                }
                else {
                    break;
                }    
            }
            // 判断是否跨年
            if (i - 1 == 12) {
                year++;
                years = 0;
                while (days >= 366) {
                    days = days - 366;
                    years++;
                }
                for (i = 1; i <= years; i++) {
                    if (!isLeapYear(year + i))
                        days++;
                }
                // 给定年的计算结束,调用reat函数
                rest(days);
            } else {
                month = i;
                day = days;
            }
        } else {
            
            day = days + day;
        }
        System.out.println(year + "/" + month + "/" + day);
    }

    // 判断是否是闰年
    public static boolean isLeapYear(int year) {
        if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
            return true;
        else
            return false;
    }

    public static void rest(int days) {
        int i;
        for (i = 1; i <= 12; i++) {
            if (days - a[i] > 0) {
                days = days - a[i];
            } else {
                month = i;
                if (!isLeapYear(year) && month >= 2) {
                    day = days + 1;
                }else {
                    day = days;
                }
                break;
            }
        }
        if (i - 1 == 12) {
            year = year + 1;
            if (!isLeapYear(year)) {
                days++;
            }
            rest(days);
        } else {

        }

        year += years;
    }
}
 

猜你喜欢

转载自blog.csdn.net/qq_30249871/article/details/100571914