提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用DateTimeFormatter类的parseBest()方法
/** 时 代 J a v a 公 众 号 - nowjava.com 提 供 **/ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.TemporalAccessor; public class Main { public static void main(String[] args) { DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'HH:mm:ss[Z]]"); parseStr(parser, "2019-05-31"); parseStr(parser, "2019-05-31T16:30:12"); parseStr(parser, "2019-05-31T16:30:12-0500"); parseStr(parser, "2019-05-31Hello"); } public static void parseStr(DateTimeFormatter formatter, String text) { try { TemporalAccessor ta = formatter.parseBest(text, OffsetDateTime::from, LocalDateTime::from, LocalDate::from);// 来自 时 代 J a v a - nowjava.com if (ta instanceof OffsetDateTime) { OffsetDateTime odt = OffsetDateTime.from(ta); System.out.println("OffsetDateTime: " + odt); } else if (ta instanceof LocalDateTime) { LocalDateTime ldt = LocalDateTime.from(ta); System.out.println("LocalDateTime: " + ldt); } else if (ta instanceof LocalDate) {