java8 LocalDate 于 LocalDateTime 将 String 转化为日期遇见的坑

java 8 中 

当使用LocalDateTime  

String regStringTime = "2013-06-25";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime parse = LocalDateTime.parse(regStringTime, dateTimeFormatter);

就会报错

 Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2013-06-25 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(LocalDateTime.java:461)
    at java.time.format.Parsed.query(Parsed.java:226)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    ... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2013-06-25 of type java.time.format.Parsed
    at java.time.LocalTime.from(LocalTime.java:409)
    at java.time.LocalDateTime.from(LocalDateTime.java:457)
    ... 4 more

当使用LocalDate时就不会报错

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 注册日期
LocalDate regTime = LocalDate.parse(regStringTime, dateTimeFormatter);
LocalDate regTime = LocalDate.parse(regStringTime, dateTimeFormatter);

java8 LocalDate 于 LocalDateTime 将 String 转化为日期遇见的坑_第1张图片

当时用 LocalDateTime 将String 转化为日期时候  一定最少要格式到秒,例如下边,则不会报错

String regStringTime = "2013-06-25 00:00:00";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse(regStringTime, dateTimeFormatter);

你可能感兴趣的:(Date)