Converting String to Date using SimpleDateFormat is returning random date [duplicate]

You are using the format pattern string yyyyMMdd. You are parsing the date-time string 2018-06-20 00:00:00.

2018 matches yyyy. MM means that month should be two chars, so -0 is taken for the month. And -0 or just 0 is taken to be the month before month 1 of 2018, that is, December 2017. Finally 6 is taken as the day of month. It should have been two chars too, but since there is only one digit, SimpleDateFormat settles with that. The remainder of the string is tacitly ignored.

Exactly the same thing happens when parsing the other string.

It’s the long outdated SimpleDateFormat class in a nutshell: In its attempts to be friendly and helpful it produces the most unpleasant and confusing surprises. Where you would have wished it would tell you something is wrong, it just pretends that everything is fine. It’s one of the main reasons that this class is considered troublesome, and why the replacement for the old classes came out with Java 8 more than 4 years ago. So just never use SimpleDateFormat again.

Instead look into java.time and its DateTimeFormatter.

Also don’t get date values as strings from your database. Depending on the datatype that the query returns get either a LocalDateTime or a LocalDate object. This will free you completely from parsing.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Leave a Comment