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: