问题
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));
Expected result: A LocalDateTime
of 2008-05-21T00:00
.
What I got instead:
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?
回答1:
The devil is in the detail. You are basically doing it correctly, except:
- You need to provide a locale for the formatter.
- By parsing into a
LocalDateTime
you are losing information and possibly getting an unexpected result.
So I suggest:
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);
Output is:
2008-05-21T00:00-04:00[America/New_York]
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”.
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
.
Links
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]
来源:https://stackoverflow.com/questions/62105691/datetimeparse-exception