java编程--03介绍关于日期常用的计算

 1     /**
 2      * 获取2个日期之间的天数差
 3      * d2-d1
 4      * @return
 5      * @throws Exception 
 6      * @Description:
 7      */
 8     public static int getDiffDays(Date d1,Date d2) throws Exception{
 9         if(null == d1 || null == d2){
10             throw new Exception("日期不允许为空");
11         }
12         if(d1.compareTo(d2) > 0){
13             throw new Exception("开始日期不能大于结束日期");
14         }
15         int daysDiff = 0;
16         Calendar cal = Calendar.getInstance();
17         Calendar cal2 = Calendar.getInstance();
18         cal.setTime(d1);
19         cal2.setTime(d2);
20         
21         int date_of_year1 = cal.get(Calendar.DAY_OF_YEAR);
22         int date_of_year2 = cal2.get(Calendar.DAY_OF_YEAR);
23         int year1 = cal.get(Calendar.YEAR);
24         int year2 = cal2.get(Calendar.YEAR);
25         if(year1 == year2 ){//同一年
26             daysDiff = (date_of_year2 - date_of_year1);
27         } else {//非同一年
28             for (int i = year1; i < year2; i++) {
29                 if(i%4==0&&i%100==0 || i%400==0){//如果是否闰年。能同时被4和100,或者被400整除的年份是闰年
30                     daysDiff += 366;
31                 } else {//如果不是闰年
32                     daysDiff += 365;
33                 }
34             }
35             daysDiff += (date_of_year2 - date_of_year1);
36         }
37         return daysDiff;
38     }
39     
40     /**
41      * 测试
42      * @param args
43      * @Description:
44      */
45     @Test
46     public void testGetDiffDays(){
47          String dateStr = "2017-11-15 1:21:28";
48             String dateStr2 = "2017-11-20 1:21:28";
49             SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
50             SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
51             try 
52             {
53                 Date date2 = format.parse(dateStr2);
54                 Date date = format.parse(dateStr);
55                 
56                 System.out.println("两个日期的差距:" + getDiffDays(date,date2));
57             } catch (Exception e) {
58                 e.printStackTrace();
59             }
60         
61     }

转载于:https://www.cnblogs.com/codetree/p/7764619.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值