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

时间:2020-03-13 15:26:27

标签: java groovy java-time

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

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,对我来说一切都很好。

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

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

我们需要使用简短的工作日(而不是“星期三”)使用德语中的“ So,Mo,Di,Mi,Do,Fr,Sa”。

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

// 2015年产量