有時候我們會遇到很多形式的日期判斷,甚至是並不常見的日期形式,比如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 於江蘇蘇州
