java – SimpleDateFormat. Parse () – generates incorrect dates for different date formats
•
Java
Here is my code for parsing dates using the simpledateformat pattern:
String pattern = "yyyy-MM-dd"; SimpleDateFormat format = new SimpleDateFormat(pattern); try { Date date = format.parse("05-21-2030"); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); }
You can see that the date I passed to the parser is different from the date format specified in simpledateformat In this case, due to different formats, I want a dismissal, but it successfully parses with some different date values I got the output – Tue Mar 22 00:00:00 ist 12
When I pass the same format, such as 2030-05-21, it works normally
Can you tell me how to stop these things in my code?
Solution
Basically, you want simpledateformat to be strict, so set lenient to false
SimpleDateFormat format = new SimpleDateFormat(pattern); format.setLenient(false);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码