Parse String for unknown TemporalAccessor

六眼飞鱼酱① 提交于 2019-12-11 06:26:40

问题


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 when the string represents a date like "2018-02-28"
  • or LocalDateTime when the string represents a timestamp like "2018-02-28T11:20:00"

The following attempt results into DateTimeParseException:

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

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?


回答1:


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.

This should work as required:

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


来源:https://stackoverflow.com/questions/49026914/parse-string-for-unknown-temporalaccessor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!