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

Era*_*ndo 0 java groovy java-time

我有这个 groovy 代码,它给了我一个错误,我不明白为什么:

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'
Run Code Online (Sandbox Code Playgroud)

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

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

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

aku*_*ykh 6

问题是您将格式化程序设置为解析/格式化,Locale.GERMAN但让它"Wed, 04 Feb 2015 10:12:34 UTC"解析。Wed对于周三的语言-英语,不是德国。

要解决问题,只需替换Locale.GERMANLocale.ENGLISH。另一种解决方案是语言环境的参数。