-
喵喔喔
您想要的是自定义方法,因为您对日期的有效性设置了特殊限制。以下通过了您的所有 4 个示例:public static boolean validDate(String date) { date = date.trim(); if (date.length() < 6) return false; String[] parts = date.split("/"); if (parts.length != 2) return false; int month = 0; try { month = Integer.parseInt(parts[0]); } catch (NumberFormatException e) { e.printStackTrace(); return false; } if (month < 1 || month > 12) return false; int year = 0; try { year = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { e.printStackTrace(); return false; } if (year < 1000) return false; return true;}public static void main(String[] args) { String s1 = "09/20"; String s2 = "13/5651"; String s3 = "3/2104"; String s4 = "03/2010"; System.out.println(s1 + " " + validDate(s1)); System.out.println(s2 + " " + validDate(s2)); System.out.println(s3 + " " + validDate(s3)); System.out.println(s4 + " " + validDate(s4));}将打印:09/20 false13/5651 false3/2104 true03/2010 true我不确定这部分:if (year < 1000) return false;如果你愿意,你可以改变它。
-
交互式爱情
public boolean isThisDateValid(String dateToValidate, String dateFromat){ if(dateToValidate == null){ return false; } SimpleDateFormat sdf = new SimpleDateFormat(dateFromat); sdf.setLenient(false); try { //if not valid, it will throw ParseException Date date = sdf.parse(dateToValidate); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); return false; } return true;}参考https://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/
-
慕哥6287543
使用YearMonth类。DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/uuuu" ) ;
YearMonth ym = YearMonth.parse( "3/2018" , f ) ;用于DateTimeParseException检测无效输入的陷阱。提示:使用标准ISO 8601格式将日期时间值作为文本进行交换。对于年月:YYYY-MM该java.time类默认使用这些标准格式。YearMonth.parse( "2018-03" )