我只是try 在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.

推荐答案

事实证明,Java不接受赤裸裸的日期值作为日期时间.使用LocalDate而不是LocalDateTime可以解决此问题:

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

Java相关问答推荐

如何在Java中对自定义协议进行主机名验证?

使用json参数通过单击jSP文件中的按钮来运行server时出现问题

在FML中删除关键帧动画

JDK22执行repackage of goal org. springframework. boot:spring—boot—maven—plugin:3.2.3:repackage failed:unsupported class file major version 66—>

SpringBootreact 式Web应用程序的Spring Cloud Configer服务器中的资源控制器损坏

当我已经安装了其他版本的Java时,如何在Mac OSX 14.3.1上安装Java 6?

在bash中将数组作为Java程序的参数传递

使用传递的参数构造异常的Mockito-doThrow(或thenThrow)

使用REST客户端和对象映射器从字符串反序列化Json

CompleteableFuture是否运行在不同的内核上?

在Java中,在单个逻辑行中连接列表和单个元素的正确方法是什么?

有没有可能在时间范围内得到多种解决方案?

允许同时执行两个方法,但不能同时执行这两个方法

Java页面筛选器问题

无法播放音频:从资源加载库GStreamer-Lite失败

如何配置空手道以使用FeignClient或RestTemplate代替ApacheHttpClient

Java 21中泛型的不兼容更改

何时调用密封层次 struct 的switch 中的默认情况

接受类及其接口的Java类型(矛盾)

Java 17与Java 8双重表示法