【问题标题】:OffsetDateTime customer parser [duplicate]OffsetDateTime 客户解析器 [重复]
【发布时间】:2021-05-25 20:00:11
【问题描述】:

您好,我尝试使用 DateTimeFormatter 将字符串 20110330174824917 解析为 OffsetDateTime

 public static void main(String[] args)  {
       // System.out.println(OffsetDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
        System.out.println(LocalDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
    }

但我明白了
线程“主”java.time.format.DateTimeParseException 中的异常:无法解析文本“20110330174824917”,在索引 8 处找到未解析的文本 在 java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952) 在 java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) 在 java.time.LocalDateTime.parse(LocalDateTime.java:492)


嘿伙计们,这个问题似乎与 java 8 有关 https://bugs.openjdk.java.net/browse/JDK-8031085

谢谢大家的帮助

【问题讨论】:

  • 好吧,您使用的是OffsetDateTime,但是您的模式和要解析的字符串都没有区域偏移量。 LocalDateTime 更适合这种情况。
  • 顺便说一句,I cannot reproduce it
  • 我尝试使用 LocalDateTime 但问题仍然出现
  • 我在主题中编辑代码也许有助于重现它
  • 我已经尝试过您的代码,并且运行良好。你用的jdk是什么版本的?

标签: java offsetdatetime


【解决方案1】:

您可以为格式化程序定义使用的Zone 并将输入字符串与正确的区域偏移量连接

// note the added Z at the end of the pattern for the offset
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSZ").withZone(ZoneId.of("UTC"));

OffsetDateTime dateTime = OffsetDateTime.parse("20110330174824917" + "+0000", formatter);

【讨论】:

    【解决方案2】:

    DateTimeFormatter#withZone

    您的日期时间字符串没有时区信息,因此,为了将其解析为OffsetDateTime,您需要明确传递时区信息。您可以使用DateTimeFormatter#withZone 将日期时间字符串解析为ZonedDateTime,您可以使用ZonedDateTime#toOffsetDateTime 将其转换为OffsetDateTime

    import java.time.OffsetDateTime;
    import java.time.ZoneId;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            String strDateTime = "20110330174824917";
            
            // Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS", Locale.ENGLISH)
                                                    .withZone(ZoneId.systemDefault());
            
            OffsetDateTime odt = ZonedDateTime.parse(strDateTime, dtf)
                                                .toOffsetDateTime();
            System.out.println(odt);
        }
    }
    

    输出:

    2011-03-30T17:48:24.917+01:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 2021-03-10
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      相关资源
      最近更新 更多