DateTimeParseException - could not be parsed at index 0

邮差的信 提交于 2021-02-09 09:20:44

问题


I'm trying to parse the following date "Wed, 26 Feb 2020 03:42:25 -0800"

String datePattern = "EEE, dd MMM yyyy HH:mm:ss Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(datePattern);
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateStr, formatter);

But i get the following error:

java.time.format.DateTimeParseException: Text 'Wed, 26 Feb 2020 03:42:25 -0800'  
could not be parsed at index 0

Thanks


回答1:


You need to provide a Locale that uses the language used by the date String. Otherwise, the formatter will take the system default locale.

See this example:

public static void main(String[] arguments) {
    String dt = "Wed, 26 Feb 2020 03:42:25 -0800";
    ZonedDateTime zdt = ZonedDateTime.parse(dt, 
            DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US));
    System.out.println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}

Output on my German system:

2020-02-26T03:42:25-08:00

Without this Locale (could be UK, too) I get the same Exception as you have got.

Addition
Good point given by @Lino: to be country-independent, better use Locale.ENGLISH because that keeps the respect to the language but doesn't depend on a specific Locale of a country or region.




回答2:


Don’t struggle with finding the right format pattern string and the right locale for your string. The formatter is built in.

    String dateStr = "Wed, 26 Feb 2020 03:42:25 -0800";
    DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
    OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateStr, formatter);

    System.out.println(offsetDateTime);

Output is:

2020-02-26T03:42:25-08:00

It works with ZonedDateTime too, but since DateTimeFormatter.RFC_1123_DATE_TIME only handles offsets (such as offset amounts or GMT), not time zones, I found OffsetDateTime more appropriate.

DateTimeFormatter.RFC_1123_DATE_TIME always expects day of week and month abbreviation in English, even no matter if you explicitly specify a different locale, because the RFC says that the string is in English. What could go wrong?



来源:https://stackoverflow.com/questions/60413413/datetimeparseexception-could-not-be-parsed-at-index-0

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