檢測任意日期字符串是否屬於當天的java實現方案


  有時候我們會遇到很多形式的日期判斷,甚至是並不常見的日期形式,比如20161212之類的日期,下面就此來進行代碼是否處於當天的日期校驗的代碼實現來做一個整理。

 1 public static boolean isToday(String str, String formatStr) throws Exception{
 2     SimpleDateFormat format = new SimpleDateFormat(formatStr);
 3     Date date = null;
 4     try {
 5         date = format.parse(str);
 6     } catch (ParseException e) {
 7         logger.error("解析日期錯誤", e);
 8     }
 9     Calendar c1 = Calendar.getInstance();              
10     c1.setTime(date);                                 
11     int year1 = c1.get(Calendar.YEAR);
12     int month1 = c1.get(Calendar.MONTH)+1;
13     int day1 = c1.get(Calendar.DAY_OF_MONTH);     
14     Calendar c2 = Calendar.getInstance(); 
15     c2.setTime(new Date());
16     int year2 = c2.get(Calendar.YEAR);
17     int month2 = c2.get(Calendar.MONTH)+1;
18     int day2 = c2.get(Calendar.DAY_OF_MONTH);   
19     if(year1 == year2 && month1 == month2 && day1 == day2){
20         return true;
21     }
22     return false;   
23 }

  上述代碼中 formatStr 是我們需要校驗的日期形式,比如我需要校驗 “20161212”是否是當天,那么formatStr為"yyyyMMdd",比如我們需要校驗“2016-12-12”是不是當天,就為“yyyy-MM-dd”,比如需要校驗“2016/12/12”的字符串,就為“yyyy/MM/dd”,依次類推即可。

非常感謝!

fullstack.yang      2016/12/12 於江蘇蘇州


免責聲明!

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



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