首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >解析LocalDateTime时无法从TemporalAccessor获取LocalDateTime (Java8)

解析LocalDateTime时无法从TemporalAccessor获取LocalDateTime (Java8)
EN

Stack Overflow用户
提问于 2014-12-13 08:04:04
回答 11查看 172.9K关注 0票数 197

我只是尝试在Java8中将日期字符串转换为DateTime对象。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime dt = LocalDateTime.parse("20140218", formatter);

我得到以下错误:

Exception in thread "main" java.time.format.DateTimeParseException: 
Text '20140218' could not be parsed: 
Unable to obtain LocalDateTime from TemporalAccessor: 
{},ISO resolved to 2014-02-18 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)

语法与here建议的语法相同,但我得到了一个例外。我正在使用JDK-8u25

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2014-12-13 08:20:21

事实证明,Java不接受纯日期值作为DateTime。使用LocalDate而不是LocalDateTime解决了这个问题:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);
票数 215
EN

Stack Overflow用户

发布于 2015-10-01 19:33:28

如果确实需要将日期转换为LocalDateTime对象,可以使用LocalDate.atStartOfDay()。这将为您提供一个指定日期的LocalDateTime对象,其中的小时、分钟和秒字段设置为0:

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();
票数 89
EN

Stack Overflow用户

发布于 2016-09-25 17:11:55

如果有人(像我一样)应该再读一遍这个主题,那么正确的答案应该是DateTimeFormatter定义,例如:

private static DateTimeFormatter DATE_FORMAT =  
            new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter(); 

如果要显示可选字段,则应设置这些字段。其余的代码应该完全相同。

票数 60
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27454025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档