为未知的TemporalAccessor解析字符串

时间:2018-02-28 10:11:01

标签: java date time java-time datetime-parsing

我收到的请求参数包含未知的时间(ISO格式的日期,时间或时间戳),并希望将其解析为java.time.temporal.TemporalAccessor

    当字符串代表LocalDate 之类的日期时,
  • "2018-02-28" 当字符串表示LocalDateTime
  • 之类的时间戳时,
  • "2018-02-28T11:20:00"

以下尝试产生DateTimeParseException

TemporalAccessor dt = DateTimeFormatter.ISO_DATE_TIME.parseBest(str, LocalDateTime::from, LocalDate::from);

确定字符串的长度或{" T"的出现,DateTimeFormatter要使用,在我看来有点hacky。以及尝试一种接一种的格式。

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您的问题是ISO_DATE_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);