无法使用"HH:mm E d MMM YYYY"解析DateTimeFormatter.图案 [英] DateTimeFormatter could not be parsed using "HH:mm E d MMM YYYY" pattern

查看:337
本文介绍了无法使用"HH:mm E d MMM YYYY"解析DateTimeFormatter.图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从外部数据源检索日期/时间,该日期/时间以以下格式返回:"5月14日星期六,5月5日",没有年份.

I am retrieving a date/time from an external data source, this is returned in the following format "14:30 Sat 05 May" with no year.

我一直试图将其解析为LocalDateTime失败.返回的数据不会返回一年,因为它假设我们始终在当年运行.

I've been trying to parse this to a LocalDateTime unsuccessfully. The data returned does not return a year as it is an assumption that we are always operating in the current year.

//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);

上面的代码引发以下异常

The above code throws the following exception

线程"main"中的异常java.time.format.DateTimeParseException:无法在索引16处解析文本"5月5日星期六14:30"

Exception in thread "main" java.time.format.DateTimeParseException: Text '14:30 Sat 05 May' could not be parsed at index 16

任何帮助表示赞赏.

推荐答案

LocalDateTime.parse()期望String代表有效日期,该日期为year部分.
通过这种方式调用此方法后,您无法设置年份:

LocalDateTime.parse() expects a String that represents a valid date, which the year part.
You cannot set the year after invoking this method in this way :

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

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

The year has to be set before because otherwise parse() throws DateTimeParseException.

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

As a workaround you may concatenate the current year in the input.

一些附加说明:

  • 您使用的模式和文本格式的输入日期不完全匹配.
  • 您没有为解析操作指定Locale.
    这意味着它将根据运行JVM的本地环境运行.
    为了确保它在任何情况下都有效,您应该指定Locale.
  • the pattern you use and the input date in textual format don't match exactly.
  • You don't specify a Locale for the parsing operation.
    It means that it will work according to the local where the JVM is run.
    To ensure that it works in any case, you should specify the 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);

这篇关于无法使用"HH:mm E d MMM YYYY"解析DateTimeFormatter.图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆