在java中验证(mm / yyyy)类型的日期格式

如何将日期格式验证MM/YYYY为字符串示例-

09/20 假

13/5651 假

3/2104 真的

03/2010 真实


阿波罗的战车
浏览 237回答 3
3回答

喵喔喔

您想要的是自定义方法,因为您对日期的有效性设置了特殊限制。以下通过了您的所有 4 个示例:public static boolean validDate(String date) {&nbsp; &nbsp; date = date.trim();&nbsp; &nbsp; if (date.length() < 6)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; String[] parts = date.split("/");&nbsp; &nbsp; if (parts.length != 2)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; int month = 0;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; month = Integer.parseInt(parts[0]);&nbsp; &nbsp; } catch (NumberFormatException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; if (month < 1 || month > 12)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; int year = 0;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; year = Integer.parseInt(parts[1]);&nbsp; &nbsp; } catch (NumberFormatException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; if (year < 1000)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; return true;}public static void main(String[] args) {&nbsp; &nbsp; String s1 = "09/20";&nbsp; &nbsp; String s2 = "13/5651";&nbsp; &nbsp; String s3 = "3/2104";&nbsp; &nbsp; String s4 = "03/2010";&nbsp; &nbsp; System.out.println(s1 + " " + validDate(s1));&nbsp; &nbsp; System.out.println(s2 + " " + validDate(s2));&nbsp; &nbsp; System.out.println(s3 + " " + validDate(s3));&nbsp; &nbsp; System.out.println(s4 + " " + validDate(s4));}将打印:09/20 false13/5651 false3/2104 true03/2010 true我不确定这部分:if (year < 1000)&nbsp; &nbsp; return false;如果你愿意,你可以改变它。

交互式爱情

public boolean isThisDateValid(String dateToValidate, String dateFromat){&nbsp; &nbsp; if(dateToValidate == null){&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);&nbsp; &nbsp; sdf.setLenient(false);&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; //if not valid, it will throw ParseException&nbsp; &nbsp; &nbsp; &nbsp; Date date = sdf.parse(dateToValidate);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(date);&nbsp; &nbsp; } catch (ParseException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}参考https://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/

慕哥6287543

使用YearMonth类。DateTimeFormatter&nbsp;f&nbsp;=&nbsp;DateTimeFormatter.ofPattern(&nbsp;"M/uuuu"&nbsp;)&nbsp;; YearMonth&nbsp;ym&nbsp;=&nbsp;YearMonth.parse(&nbsp;"3/2018"&nbsp;,&nbsp;f&nbsp;)&nbsp;;用于DateTimeParseException检测无效输入的陷阱。提示:使用标准ISO 8601格式将日期时间值作为文本进行交换。对于年月:YYYY-MM该java.time类默认使用这些标准格式。YearMonth.parse(&nbsp;"2018-03"&nbsp;)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java