无法使用“HH:mm E d MMM YYYY”模式解析DateTimeFormatter

时间:2018-05-09 15:29:16

标签: java parsing time java-time

我正在从外部数据源检索日期/时间,这将以下列格式“5月5日星期六14:30”返回,没有年份。

我一直试图将此解析为LocalDateTime失败。返回的数据不会返回一年,因为我们假设我们一直在当年运营。

//date to parse
String time = "14:30 Sat 05 May";

//specify date format matching above string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm E d MMM YYYY") ;

//we do not have a year returned but i can make the assumption we use the current year
LocalDateTime formatDateTime = LocalDateTime.parse(time, formatter).withYear(2018);

以上代码抛出以下异常

线程中的异常“main”java.time.format.DateTimeParseException:Text '14:30 Sat 05 May'无法在索引16处解析

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:3)

LocalDateTime.parse()预计String代表有效日期,year部分。 以这种方式调用此方法后,您无法设置年份:

LocalDateTime.parse(time, formatter).withYear(2018);

必须先设置年份,否则parse()会抛出DateTimeParseException

作为一种解决方法,您可以在输入中连接当前年份。

一些补充说明:

  • 您使用的模式和文本格式的输入日期并不完全匹配。
  • 您没有为解析操作指定Locale 这意味着它将根据运行JVM的本地工作 为了确保它在任何情况下都有效,您应该指定Locale

所以你可以尝试类似的东西:

//date to parse
String time = "14:30 Sat 05 May";
time +=  " " + LocalDate.now().getYear();

//specify date format matching above string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm EEE dd MMM yyyy", Locale.US) ;

//we do not have a year returned but i can make the assumption we use the current year
LocalDateTime formatDateTime = LocalDateTime.parse(time, formatter);

答案 1 :(得分:3)

默认年份

使用DateTimeFormatter课程,通过调用DateTimeFormatterBuilder并使用parseDefaulting指定年份字段,在ChronoField.YEAR中指定默认年份。

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("HH:mm E d MMM")
    .parseDefaulting(ChronoField.YEAR, 2018)  // <------
    .toFormatter(Locale.ENGLISH);

使用此格式化程序代替您的格式化程序:

LocalDateTime.parse( "14:30 Sat 05 May" , formatter ) 

......我明白了:

  

2018-05-05T14:30

code run live at IdeOne.com

注意事项:

  • 您的格式模式字符串需要与解析后的字符串端对端匹配。因此,当您的日期时间字符串中没有一年时,请不要在格式模式中包含YYYY
  • 在任何情况下都不要在这里使用大写YYYY。它是基于周的年份,仅适用于周数。如果您的字符串中包含一年,则应使用uuuu或小写yyyy
  • 习惯为格式化程序提供明确的区域设置,以便您知道它也可以在其他计算机上运行,​​并在有一天使用其设置时在您的格式化程序上运行。