检测任意日期字符串是否属于当天的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 于江苏苏州

posted @ 2016-12-12 21:35  fullStack-yang  阅读(8679)  评论(0编辑  收藏  举报