public static boolean isDate(String dttm, String format) { boolean retValue = false; if (dttm == null || dttm.isEmpty() || format == null || format.isEmpty()) { return retValue; } String regFormat = format; regFormat = regFormat.replaceAll("(^')|('$)", ""); regFormat = regFormat.replaceAll("'([^'])", "$1"); regFormat = regFormat.replace("''", "'"); regFormat = regFormat.replace("\", "\\"); regFormat = regFormat.replaceAll("[MdHmsS] ", "\\d "); regFormat = regFormat.replaceAll("[y] ", "\\d{1,4}"); if (!dttm.matches("^" regFormat "$")) { return false; } SimpleDateFormat formatter = new SimpleDateFormat(format); formatter.setLenient(false); try { formatter.parse(dttm); retValue = true; } catch (ParseException e) { } return retValue; } 上面的代码只对应了yMdHmsS,虽然对当时的系统已经足够了,但还是感觉不太爽,觉得应该有一种通用的方法。于是查Java的API,发现parse方法还有一个带参数的方法。理解了它的使用方法之后,把代码改成下面的样子
代码如下 | 复制代码 | private static boolean isDate(String dttm, String format) { if (dttm == null || dttm.isEmpty() || format == null || format.isEmpty()) { return false; } DateFormat formatter = new SimpleDateFormat(format); formatter.setLenient(false); ParsePosition pos = new ParsePosition(0); Date date = formatter.parse(dttm, pos); if (date == null || pos.getErrorIndex() > 0) { return false; } if (pos.getIndex() != dttm.length()) { return false; } return true; } 本来以为这样应该万事大吉了,但之后的测试又发现两个Bug。一个是,当输入的日期没有年份(需求是没有输入年份是默认当前年份)时,默认取的是1970年,这样的话,如果当年是闰年的话,2/29号就验证出错了;另一个是Java的日期和Oracle的日期大小不同,Oracle好像最大只支持到9999年,而Java可以有2万多年。所以代码又被改成了下面的样子
代码如下 | 复制代码 | private static boolean isDate(String dttm, String format) { if (dttm == null || dttm.isEmpty() || format == null || format.isEmpty()) { return false; } if (format.replaceAll("'. ?'", "").indexOf("y") < 0) { format = "/yyyy"; DateFormat formatter = new SimpleDateFormat("/yyyy"); dttm = formatter.format(new Date()); } DateFormat formatter = new SimpleDateFormat(format); formatter.setLenient(false); ParsePosition pos = new ParsePosition(0); Date date = formatter.parse(dttm, pos); if (date == null || pos.getErrorIndex() > 0) { return false; } if (pos.getIndex() != dttm.length()) { return false; } if (formatter.getCalendar().get(Calendar.YEAR) > 9999) { return false; } return true; } |
|
|