日期:2014-05-20 浏览次数:20795 次
public boolean t(Date d, String s) { String[] sa = s.split(" "); //把格式化字符串分割 Calendar c = Calendar.getInstance(); c.setTime(d); int[] dt = new int[5]; //获取Date对象的年 月 日 时 分 dt[0] = c.get(Calendar.MINUTE); dt[1] = c.get(Calendar.HOUR_OF_DAY); dt[2] = c.get(Calendar.DATE); dt[3] = c.get(Calendar.MONTH) + 1; dt[4] = c.get(Calendar.YEAR); boolean result = true; for (int i=0; i<dt.length && i<sa.length; i++) { if (sa[i].matches("\\d+")) { //如果格式化字符串是数字 result &= (dt[i]==Integer.valueOf(sa[i]).intValue()); } else (! "*".equals(sa[i])) { //如果格式化字符串不是*号 result = false; } } return result; }
------解决方案--------------------
这个应该能解决你说的缺省的情况
public static void main(String args[]) throws Exception{ Date date = new Date(); System.out.println(t(date,"07 * * * *")); } public static boolean t(Date date,String s) { SimpleDateFormat sdf = new SimpleDateFormat("mm HH dd MM yyyy"); String strDate = sdf.format(date); System.out.println(strDate); String regex = getRegex(s); Matcher m = Pattern.compile(regex).matcher(strDate); return m.matches(); } private static String getRegex(String str){ String[] strings = str.split("\\s+"); if(strings.length != 5){ String[] ss = {"*","*","*","*","*"}; for(int i = 0; i < strings.length; i++){ ss[i] = strings[i]; } StringBuilder sb = new StringBuilder(); for(int i = 0; i < ss.length; i++){ if(i == ss.length - 1){ sb.append(ss[i]); }else{ sb.append(ss[i]).append(" "); } } str = sb.toString(); } str = str.replaceAll("\\s+", "\\\\s+?"); str = str.replaceAll("\\*", "\\\\d+?"); return str; }