java中计算两个日期之间天数

//用java编写出一个以下方法计算两个日期之间天数的程序设计。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo4 {
    public static void main(String[] args) {
        try {
            System.out.println(相差天数("2016-11-30", "2016-5-31"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Pattern p = Pattern.compile("(\\d{4})-(\\d{1,2})-(\\d{1,2})");

    public static int 相差天数(String a, String b) throws Exception {
        Matcher m = p.matcher(a);
        if (!m.matches())
            throw new Exception();
        int y1 = Integer.parseInt(m.group(1));
        int m1 = Integer.parseInt(m.group(2));
        int d1 = Integer.parseInt(m.group(3));
        m = p.matcher(b);
        if (!m.matches())
            throw new Exception();
        int y2 = Integer.parseInt(m.group(1));
        int m2 = Integer.parseInt(m.group(2));
        int d2 = Integer.parseInt(m.group(3));
        return 相差天数(y1, m1, d1, y2, m2, d2);
    }

    public static int 相差天数(int y1, int m1, int d1, int y2, int m2, int d2) {
        return 总第几天(y1, m1, d1) - 总第几天(y2, m2, d2);
    }

    public static int 总第几天(int y, int m, int d) {
        int a = (y - 1) * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400;
        return a + 年第几天(y, m, d);
    }

    public static int 年第几天(int y, int m, int d) {
        return 闰年(y) ? 润年月前天数[m] + d : 平年月前天数[m] + d;
    }

    public static boolean 闰年(int 年) {
        return 年 % 400 == 0 || (年 % 4 == 0 && 年 % 100 != 0);
    }

    private static final int[] 平年月天数 = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    private static final int[] 平年月前天数 = new int[14], 润年月前天数 = new int[14];
    static {
        int n = 0;
        for (int i = 1; i <= 12; i++) {
            平年月前天数[i] = n;
            润年月前天数[i] = i > 2 ? n + 1 : n;
            n += 平年月天数[i];
        }
        平年月前天数[13] = n;
        润年月前天数[13] = n + 1;
    }
}
原文地址:https://www.cnblogs.com/interdrp/p/15725890.html