码迷,mamicode.com
首页 > 编程语言 > 详细

Java中计算两个字符串日期之间或当前时间与指定时间的天数差

时间:2020-02-15 09:24:46      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:ring   simple   字符   parse   class   except   rgs   mamicode   ati   

 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     }

技术图片

Java中计算两个字符串日期之间或当前时间与指定时间的天数差

标签:ring   simple   字符   parse   class   except   rgs   mamicode   ati   

原文地址:https://www.cnblogs.com/xieshilin/p/12310356.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!