现在需要在java文件中校验日期是否符合yyyy-mm-dd格式并且为有效日期,也就是说不能出现0000-00-00这种的错误形式,请问有没有什么好办法?另外,还要校验时间格式,时间格式为 xx:xx:xx,时间不允许出现24:00:00这种情况。请问有没有对这方面比较牛的,麻烦给解答一下了 :idea:
6条回答 默认 最新
- _1_1_7_ 2012-08-30 16:22关注
[code="java"]
static int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; /** * @param date yyyy-MM-dd HH:mm:ss * @return */ public static boolean isValidDate(String date) { try { int year = Integer.parseInt(date.substring(0, 4)); if (year <= 0) return false; int month = Integer.parseInt(date.substring(5, 7)); if (month <= 0 || month > 12) return false; int day = Integer.parseInt(date.substring(8, 10)); if (day <= 0 || day > DAYS[month]) return false; if (month == 2 && day == 29 && !isGregorianLeapYear(year)) { return false; } int hour = Integer.parseInt(date.substring(11, 13)); if (hour < 0 || hour > 23) return false; int minute = Integer.parseInt(date.substring(14, 16)); if (minute < 0 || minute > 59) return false; int second = Integer.parseInt(date.substring(17, 19)); if (second < 0 || second > 59) return false; } catch (Exception e) { e.printStackTrace(); return false; } return true; } public static final boolean isGregorianLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } public static void main(String[] args) { System.out.println(isValidDate("2100-02-29 23:00:01")); }
[/code]
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报