Is there a way to parse two different dateTime formats into LocalDateTime or Instant in java?

99封情书 提交于 2020-06-17 13:08:27

问题


How can we validate two formats "yyyy-MM-dd" and "yyyy-MM-dd'T'HH:mm:SSX" for a given string which can be of any of the two formats and either convert it to Instant or LocalDateTime?

LocalDateTime dateTime;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd[\'T\'HH:mm:SSX]");
    TemporalAccessor temporalAccessor = formatter.parseBest(now, LocalDateTime::from, LocalDate::from);
    if (temporalAccessor instanceof LocalDateTime) {
      dateTime = (LocalDateTime)temporalAccessor;
    } else {
      dateTime = ((LocalDate)temporalAccessor).atStartOfDay();
    }

When using the above format it's always resolving to LocalDate and chopping the time part.


回答1:


Changing the format to "yyyy-MM-dd[\'T\'HH:mm:ssX]" fixed it.



来源:https://stackoverflow.com/questions/62137376/is-there-a-way-to-parse-two-different-datetime-formats-into-localdatetime-or-ins

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