Java 8 –无法从TemporalAccessor获取LocalDateTime

将String转换为LocalDateTime的示例,但会提示以下错误:

Java8Example.java
package com.mkyong.demo;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Java8Example {

    public static void main(String[] args) {

        String str = "31-Aug-2020";

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);

        LocalDateTime localDateTime = LocalDateTime.parse(str, dtf);

        System.out.println(localDateTime);

    }
}

输出量

Exception in thread "main" java.time.format.DateTimeParseException: Text '31-Aug-2020' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
	at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
	at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
	at com.mkyong.demo.Java8Example.main(Java8Example.java:15)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
	at java.base/java.time.LocalDateTime.from(LocalDateTime.java:461)
	at java.base/java.time.format.Parsed.query(Parsed.java:235)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
	... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
	at java.base/java.time.LocalTime.from(LocalTime.java:431)
	at java.base/java.time.LocalDateTime.from(LocalDateTime.java:457)
	... 4 more

31-Aug-2020的日期没有时间进行修复,请使用LocalDate.parse(str, dtf).atStartOfDay()

String str = "31-Aug-2020";

  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);

  LocalDateTime localDateTime = LocalDate.parse(str, dtf).atStartOfDay();

参考文献

翻译自: https://mkyong.com/java8/java-8-unable-to-obtain-localdatetime-from-temporalaccessor/

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值