java.time.format.DateTimeParseException:无法在索引0处解析文本

问题描述 投票:0回答:1

我有这个时髦的代码,给我一个错误,我不明白为什么:

import java.text.SimpleDateFormat
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters

static String convertDateTimeString(String fromFormat, String toFormat, String dateString) {
    DateTimeFormatter fromFormatter = DateTimeFormatter.ofPattern(fromFormat, Locale.GERMAN)
    LocalDateTime localDateTime = LocalDateTime.parse(dateString, fromFormatter)
    DateTimeFormatter toFormatter = DateTimeFormatter.ofPattern(toFormat, Locale.GERMAN)
    localDateTime.format(toFormatter)
}

String date = convertDateTimeString( 'EEE, dd MMM yyyy HH:mm:ss z', 'yyyy', "Wed, 04 Feb 2015 10:12:34 UTC")
assert date == '2015'

错误提示java.time.format.DateTimeParseException: Text 'Wed, 04 Feb 2015 10:12:34 UTC' could not be parsed at index 0

但是我检查了JavaDocs,对我来说一切都很好。

你能告诉我这里是什么问题吗?

java groovy java-time
1个回答
2
投票

问题是您将格式化程序设置为Locale.GERMAN进行解析/格式化,但给了"Wed, 04 Feb 2015 10:12:34 UTC"进行解析。 Wed用于星期三,它是英语,而不是德语。

要解决该问题,只需将Locale.GERMAN替换为Locale.ENGLISH。另一个解决方案是使用语言环境的参数。

© www.soinside.com 2019 - 2024. All rights reserved.