Java8- ZonedDateTime,DateTimeFormatter无法识别格式 [英] Java8- ZonedDateTime with DateTimeFormatter not recognizing the format

查看:181
本文介绍了Java8- ZonedDateTime,DateTimeFormatter无法识别格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ZonedDateTime和Java 8的DateTimeFormatter。当我尝试解析自己的模式时,它无法识别并抛出异常。

I am using the ZonedDateTime with DateTimeFormatter of Java 8. When I try to parse my own pattern it doesn't recognizes and throws an exception.

    String oraceDt = "1970-01-01 00:00:00.0";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
    ZonedDateTime dt = ZonedDateTime.parse(oraceDt, formatter);

Exception in thread "main" java.time.format.DateTimeParseException: Text '1970-01-01 00:00:00.0' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1970-01-01T00:00 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.ZonedDateTime.parse(ZonedDateTime.java:597)
at com.timezone.Java8DsteTimes.testZonedDateTime(Java8DsteTimes.java:31)
at com.timezone.Java8DsteTimes.main(Java8DsteTimes.java:11)

引起: java.time.DateTimeException:无法从TemporalAccessor获取ZonedDateTime:{},ISO解析为1970-01-01T00:00类型java.time.format.Parsed

Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1970-01-01T00:00 of type java.time.format.Parsed

推荐答案

嗯,你想要创建一个 ZonedDateTime ,它总是引用一个时区,但你的输入不包含这样的如果输入缺少区域,您也没有指示格式化程序使用默认时区。您的问题有两种解决方案:

Well, you want to create a ZonedDateTime which always refers to a timezone but your input does not contain such an information, and you have also not instructed your formatter to use a default timezone if the input is missing a zone. There are two solutions for your problem:


  1. 指示您的解析器使用时区(此处使用系统tz作为例)

String oraceDt = "1970-01-01 00:00:00.0";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
ZonedDateTime zdt = 
  ZonedDateTime.parse(oraceDt, formatter.withZone(ZoneId.systemDefault()));
System.out.println(zdt); // in my default zone => 1970-01-01T00:00+01:00[Europe/Berlin]


  • 使用不需要时区的其他结果类型(此处 LocalDateTime

  • Use another result type which does not need a timezone (here LocalDateTime):

    String oraceDt = "1970-01-01 00:00:00.0";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
    LocalDateTime ldt = LocalDateTime.parse(oraceDt, formatter);
    System.out.println(ldt); // 1970-01-01T00:00
    


  • 这篇关于Java8- ZonedDateTime,DateTimeFormatter无法识别格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆