1 //用java编写出一个以下方法计算两个日期之间天数的程序设计。
2
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5
6 public class Demo4 {
7 public static void main(String[] args) {
8 try {
9 System.out.println(相差天数("2016-11-30", "2016-5-31"));
10 } catch (Exception e) {
11 e.printStackTrace();
12 }
13 }
14
15 private static Pattern p = Pattern.compile("(\\d{4})-(\\d{1,2})-(\\d{1,2})");
16
17 public static int 相差天数(String a, String b) throws Exception {
18 Matcher m = p.matcher(a);
19 if (!m.matches())
20 throw new Exception();
21 int y1 = Integer.parseInt(m.group(1));
22 int m1 = Integer.parseInt(m.group(2));
23 int d1 = Integer.parseInt(m.group(3));
24 m = p.matcher(b);
25 if (!m.matches())
26 throw new Exception();
27 int y2 = Integer.parseInt(m.group(1));
28 int m2 = Integer.parseInt(m.group(2));
29 int d2 = Integer.parseInt(m.group(3));
30 return 相差天数(y1, m1, d1, y2, m2, d2);
31 }
32
33 public static int 相差天数(int y1, int m1, int d1, int y2, int m2, int d2) {
34 return 总第几天(y1, m1, d1) - 总第几天(y2, m2, d2);
35 }
36
37 public static int 总第几天(int y, int m, int d) {
38 int a = (y - 1) * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400;
39 return a + 年第几天(y, m, d);
40 }
41
42 public static int 年第几天(int y, int m, int d) {
43 return 闰年(y) ? 润年月前天数[m] + d : 平年月前天数[m] + d;
44 }
45
46 public static boolean 闰年(int 年) {
47 return 年 % 400 == 0 || (年 % 4 == 0 && 年 % 100 != 0);
48 }
49
50 private static final int[] 平年月天数 = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
51
52 private static final int[] 平年月前天数 = new int[14], 润年月前天数 = new int[14];
53 static {
54 int n = 0;
55 for (int i = 1; i <= 12; i++) {
56 平年月前天数[i] = n;
57 润年月前天数[i] = i > 2 ? n + 1 : n;
58 n += 平年月天数[i];
59 }
60 平年月前天数[13] = n;
61 润年月前天数[13] = n + 1;
62 }
63 }