解析 LocalDateTime (Java 8) 时无法从 TemporalAccessor 获取 LocalDateTime

编程入门 行业动态 更新时间:2024-10-11 15:13:26
本文介绍了解析 LocalDateTime (Java 8) 时无法从 TemporalAccessor 获取 LocalDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只是想在 Java 8 中将日期字符串转换为 DateTime 对象.运行以下几行:

I am simply trying to convert a date string into a DateTime object in Java 8. Upon running the following lines:

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)

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

The syntax is identical to what has been suggested here, yet I am served with an exception. I am using JDK-8u25.

推荐答案

事实证明 Java 不接受一个裸 Date 值作为 DateTime.使用 LocalDate 而不是 LocalDateTime 解决了这个问题:

It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:

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

更多推荐

解析 LocalDateTime (Java 8) 时无法从 TemporalAccessor 获取 LocalDateTime

本文发布于:2023-10-29 00:56:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538232.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:LocalDateTime   Java   TemporalAccessor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!