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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//用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;
    }
}

 

posted @   锐洋智能  阅读(154)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
· Windows 提权-UAC 绕过
历史上的今天:
2014-12-24 3种LVS/Nginx/HAProxy负载均衡器的对比分析
点击右上角即可分享
微信分享提示