validating a date using dateformat [duplicate]

眉间皱痕 提交于 2019-12-02 05:12:29

问题


I am trying to validate a date which is actually a string, trying to print it in yyyy/MM/dd format. Here is the code.

String s="2012/12/0390990";
SimpleDateFormat ft = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(ft.format(ft.parse(s))); 

and the output is 3083/05/30. I want to have the validations too. No clue how to proceed.


回答1:


It's by default lenient. You need to set it non-lenient before parsing.

ft.setLenient(false);

This will result in a ParseException when an invalid day and/or month is been supplied as compared to the year. Note that this doesn't validate the year itself as basically any number of years is valid. Depending on the concrete functional requirement, you might want to do an additional check on the year, e.g. split string on / and then check if the length of the 1st part is 4.




回答2:


You might better use a RegExp to validate input,
see for example this answer:
https://stackoverflow.com/a/2149692/1448704

Sebastian



来源:https://stackoverflow.com/questions/13057464/validating-a-date-using-dateformat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!