DateTimeParse异常 [英] DateTimeParse Exception
问题描述
解析日期时,我的代码中不断出现异常错误. 日期看起来像这样:
I am constantly getting an exception error in my code when parsing a date. The Date looks like this:
Wed May 21 00:00:00 EDT 2008
这是尝试阅读它的代码:
This is the code for trying to read it:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");
Property property = new Property();
property.setSale_date(LocalDateTime.parse(linesplit[8], formatter));
预期结果:2008-05-21T00:00
的LocalDateTime
.
我得到的是:
线程"main"中的异常java.time.format.DateTimeParseException: 无法在索引0处解析文本"2008年5月21日星期三00:00:00 EDT"
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Wed May 21 00:00:00 EDT 2008' could not be parsed at index 0
我这样做是完全错误的吗?
Am I doing this completely wrong?
推荐答案
细节在于魔鬼.您基本上可以正确执行此操作,除了:
The devil is in the detail. You are basically doing it correctly, except:
- 您需要为格式化程序提供一个语言环境.
- 通过解析为
LocalDateTime
,您正在丢失信息,并且可能会得到意外的结果.
- You need to provide a locale for the formatter.
- By parsing into a
LocalDateTime
you are losing information and possibly getting an unexpected result.
所以我建议:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
String linesplit8 = "Wed May 21 00:00:00 EDT 2008";
ZonedDateTime zdt = ZonedDateTime.parse(linesplit8, formatter);
System.out.println(zdt);
输出为:
2008-05-21T00:00-04:00 [美国/纽约]
2008-05-21T00:00-04:00[America/New_York]
您的字符串是英语.看起来像Date.toString()
的输出(Date
是Java 8之前的时间使用的老式类).所以可能是英文,因为toString
方法总是产生英文输出.因此,如果您的语言环境不是说英语的地方,则认为解析失败,并且我相信这就是这样做的原因.在这种情况下,最好将Locale.ROOT
设置为中性的英语环境.一种说不要在这里应用任何特定于语言环境的处理"的方式.
Your string is in English. It looks like the output from Date.toString()
(Date
being the old-fashioned class used for times before Java 8). So it’s probably in English because that toString
method always produced English output. So if your locale is not an English-speaking one, parsing is deemed to fail, and I believe this is the reason why it did. In this case it’s appropriate to use Locale.ROOT
for the locale neutral English-speaking locale. A way to say "don’t apply any locale specific processing here".
您的字符串包含时区缩写EDT,它是标识唯一时间点的一部分,因此您也将希望提取这部分信息.因此,请使用ZonedDateTime
.
Your string contains a time zone abbreviation, EDT, which is part of identifying a unique point in time, so you will want to pick up this part of the information too. Therefore use a ZonedDateTime
.
有一些相关/相似的问题,例如:
There are some related/similar questions, for example:
- how to parse output of new Date().toString()
- java DateTimeFormatterBuilder fails on testtime
- How do I Date format for dd MMM yyyy, as in 01 Apr 2020 [duplicate]
这篇关于DateTimeParse异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!