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

天大地大妈咪最大 提交于 2019-11-27 08:52:17

问题


This question already has an answer here:

  • String to Date Conversion mm/dd/yy to YYYY-MM-DD in java [duplicate] 5 answers
  • Parsing from String to Date throws Unparsable Date Error 3 answers

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.


回答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.




回答2:


Seems like your pattern doesn't match stringDates you passing. Try to use:

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


来源:https://stackoverflow.com/questions/50513135/converting-string-to-date-using-simpledateformat-is-returning-random-date

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