使用SimpleDateFormat将字符串转换为日期将返回随机日期 [英] Converting String to Date using SimpleDateFormat is returning random date

查看:123
本文介绍了使用SimpleDateFormat将字符串转换为日期将返回随机日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下行为感到非常困惑.我要从方法中以字符串形式返回2个日期:

I'm very confused by the following behaviour. I am returning 2 dates as Strings from a method:

 getLastSupplierFlightResults()

我添加了一个屏幕快照,分别显示返回的日期为"2018-06-20 00:00:00"和"2018-06-24 00:00:00",并保留了调试跟踪以显示值.

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.

我只是想将日期转换为20180620格式.

I simply want to convert the dates into 20180620 format.

方法:

.withStartDate()
.withEndDate()

...接受字符串值

我不明白"2017年12月6日星期三00:00:00 GMT"的日期是哪里?这是最终作为20171206传递到.withStart和.withEnd方法的值.

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.

推荐答案

您正在使用格式模式字符串yyyyMMdd.您正在解析日期时间字符串2018-06-20 00:00:00.

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

2018匹配yyyy. MM表示月份应为两个字符,因此该月份采用-0.并且-0或仅将0表示为2018年第1个月的前一个月,即2017年12月.最后,将6视为一个月中的某一天.它也应该是两个字符,但是由于只有一位,所以SimpleDateFormat用这个数字来解决.字符串的其余部分被默认忽略.

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.

简而言之,这是已经过时的SimpleDateFormat类:在尝试友好和乐于助人的过程中,它会产生最令人不愉快和令人困惑的惊喜.在您希望它告诉您有什么问题的地方,它只是假装一切都很好.这是导致此类麻烦的主要原因之一,也是4年前Java 8取代旧类的原因.因此,永远不要再使用SimpleDateFormat.

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.

请改为查看java.time及其DateTimeFormatter.

也不要从数据库中获取日期值作为字符串.根据查询返回的数据类型,获取LocalDateTimeLocalDate对象.这将使您完全摆脱解析.

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.

链接: Oracle教程:日期时间解释如何使用java.time.

这篇关于使用SimpleDateFormat将字符串转换为日期将返回随机日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆