解析未知的TemporalAccessor的字符串 [英] Parse String for unknown TemporalAccessor
问题描述
我收到的请求参数具有未知的时间(ISO格式的日期,时间或时间戳记),并想将其解析为 java.time.temporal.TemporalAccessor
:
I'm getting a request parameter with unknown temporal (date, time or timestamp in ISO format) and want to parse it into a java.time.temporal.TemporalAccessor
:
-
LocalDate
,当字符串表示日期时,例如当字符串表示像<$ c这样的时间戳记时, 2018-02-28
- 或
LocalDateTime
$ c> 2018-02-28T11:20:00
LocalDate
when the string represents a date like"2018-02-28"
- or
LocalDateTime
when the string represents a timestamp like"2018-02-28T11:20:00"
以下尝试导致 DateTimeParseException
:
TemporalAccessor dt = DateTimeFormatter.ISO_DATE_TIME.parseBest(str, LocalDateTime::from, LocalDate::from);
确定字符串的长度或出现 T,其中 DateTimeFormatter
的使用,在我看来有点不客气。
Deciding on the length of the string or the occurrence of a "T", which DateTimeFormatter
to use, seems to me a little bit hacky. As well as trying one format after another.
还有更好的解决方案吗?
Any better solution?
推荐答案
您的问题是,正如名称所示, ISO_DATE_TIME
需要一个时间。在您的情况下,您需要在模式中使用可选部分。
Your problem is that ISO_DATE_TIME
expects a time, as the name indicates. In your case you need to use an optional section in your pattern.
这应按要求工作:
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);
这篇关于解析未知的TemporalAccessor的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!