DateTimeParseException-无法在索引0处解析 [英] DateTimeParseException - could not be parsed at index 0
问题描述
我正在尝试解析以下日期"Wed, 26 Feb 2020 03:42:25 -0800"
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
谢谢
推荐答案
您需要提供使用日期String
所使用语言的Locale
.否则,格式化程序将采用系统默认的语言环境.
You need to provide a Locale
that uses the language used by the date String
. Otherwise, the formatter will take the system default locale.
请参见以下示例:
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
如果没有这个Locale
(也可能是UK
),我得到的Exception
与您得到的相同.
Without this Locale
(could be UK
, too) I get the same Exception
as you have got.
添加
@Lino的要点是:要与国家/地区无关,最好使用Locale.ENGLISH
,因为这会保持对语言的尊重,但并不依赖于某个国家或地区的特定Locale
.
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.
这篇关于DateTimeParseException-无法在索引0处解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!