Java 分析未知临时Accessor的字符串
我得到一个带有未知时态(日期、时间或ISO格式的时间戳)的请求参数,并希望将其解析为Java 分析未知临时Accessor的字符串,java,date,time,java-time,datetime-parsing,Java,Date,Time,Java Time,Datetime Parsing,我得到一个带有未知时态(日期、时间或ISO格式的时间戳)的请求参数,并希望将其解析为java.time.temporal.TemporalAccessor: LocalDate当字符串表示类似于的日期“2018-02-28” 或LocalDateTime当字符串表示时间戳时,如“2018-02-28811:20:00” 以下尝试导致DateTimeParseException: TemporalAccessor dt = DateTimeFormatter.ISO_DATE_TIME.par
java.time.temporal.TemporalAccessor
:
当字符串表示类似于LocalDate
的日期“2018-02-28”
- 或
当字符串表示时间戳时,如LocalDateTime
“2018-02-28811:20:00”
DateTimeParseException
:
TemporalAccessor dt = DateTimeFormatter.ISO_DATE_TIME.parseBest(str, LocalDateTime::from, LocalDate::from);
在我看来,决定使用DateTimeFormatter
的字符串长度或“T”的出现似乎有点老套。以及尝试一种又一种格式
有更好的解决方案吗?您的问题是
ISO\u DATE\u TIME
需要一个时间,正如名称所示。在您的情况下,您需要在模式中使用可选部分
这应按要求进行:
DateTimeFormatter FMT = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.optionalStart() //HERE WE INDICATE THAT THE TIME IS OPTIONAL
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
String input = "2018-02-28";
TemporalAccessor dt = FMT.parseBest(input, LocalDateTime::from, LocalDate::from);
你能在你的问题中列出可能的输入吗?