Java中計算兩個字符串日期之間或當前時間與指定時間的天數差


 1  public static void main(String[] args) throws ParseException {
 2         /**
 3          * 獲取當前時間
 4          *
 5          */
 6         Date date = new Date();
 7         /**轉換提日期輸出格式*/
 8         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 9 
10 
11         String a = "2020-01-01"; // 時間字符串
12         String b = dateFormat.format(date);
13 
14         Long between_dayInteger = between_days(a, b);
15 
16         System.out.println(between_dayInteger);
17 
18     }
19 
20     public static Long between_days(String a, String b) {
21 
22         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 自定義時間格式
23 
24         Calendar calendar_a = Calendar.getInstance();// 獲取日歷對象
25         Calendar calendar_b = Calendar.getInstance();
26 
27         Date date_a = null;
28         Date date_b = null;
29 
30         try {
31             date_a = simpleDateFormat.parse(a);//字符串轉Date
32             date_b = simpleDateFormat.parse(b);
33             calendar_a.setTime(date_a);// 設置日歷
34             calendar_b.setTime(date_b);
35         } catch (ParseException e) {
36             e.printStackTrace();//格式化異常
37         }
38 
39         long time_a = calendar_a.getTimeInMillis();
40         long time_b = calendar_b.getTimeInMillis();
41 
42         long between_days = (time_b - time_a) / (1000 * 3600 * 24);//計算相差天數
43 
44         return between_days;
45     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM