Converting String to Date using SimpleDateFormat is returning random date [duplicate]
I'm very confused by the following behaviour. I am returning 2 dates as Strings from a method:
getLastSupplierFlightResults()
I have added a screenshot showing the returned dates as "2018-06-20 00:00:00" and "2018-06-24 00:00:00" respectively and left the debug trace in to show the values.
I simply want to convert the dates into 20180620 format.
The methods:
.withStartDate()
.withEndDate()
...accept String values
What I don't understand is where the date "Wed Dec 06 00:00:00 GMT 2017" is coming from? This is the value that ends up being passed into the .withStart and .withEnd methods as 20171206.
As always, there is probably a simpler way of achieving my aims.
Solution 1:
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
.