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     }

posted on 2017-11-01 01:01  lukelin1989  阅读(252)  评论(0编辑  收藏  举报

导航