【问题标题】:convert instant to LocalDate and got java.time.DateTimeException: Invalid value for Year [closed]将即时转换为 LocalDate 并得到 java.time.DateTimeException: Invalid value for Year [关闭]
【发布时间】:2021-03-05 15:09:54
【问题描述】:

我将 Instant 转换为 LocalDate,这是我的实现:

theInstant.atZone(ZoneId.systemDefault()).toLocalDate();

但是,我在 Junit 测试中遇到了异常: java.time.DateTimeException:年的值无效(有效值-999999999 - 999999999):-1000000000

谁能帮忙?

谢谢!

【问题讨论】:

  • 您是如何创建Instant 的?也可以在这里看到 JUnit 测试...此外,您已将 Instant 转换为 ZonedDateTime 通过 .atZone(...) 然后通过 .toLocalDate() 提取日期部分。
  • 这种重现错误Instant.MIN.atZone(ZoneId.systemDefault());
  • atZone 方法描述为An exception will be thrown if the instant is toolarge to fit into a zoned date-time.
  • 帮助我们为您提供帮助。 theInstant 包含什么?
  • 还有 10 亿年前的瞬间有什么意义?

标签: java junit java-time localdate java.time.instant


【解决方案1】:

问题在于,无论您提供什么瞬间,它都必须在-999999999 to 999999999 的范围内,其中0 是纪元。您可以通过多种方式创建瞬间。一种是指定当前日期。

LocalDate ld = Instant.now().atZone(ZoneId.systemDefault()).toLocalDate();      
System.out.println(ld);

打印

2021-03-05

另一个是在某个时间单位内给它一个值。这是几秒钟。

    LocalDate ld = Instant.ofEpochSecond(1229998889L)
           .atZone(ZoneId.systemDefault()).toLocalDate();

打印

2008-12-22
            

【讨论】:

    【解决方案2】:

    一旦你有LocatDate

        LocalDate localDate = LocalDate.now();  //local date
    
        LocalDateTime localDateTime = localDate.atTime(10, 45, 56);  //Add time information
    
        ZoneId zoneId = ZoneId.of("Asia/Kolkata"); // Zone information you can present ZoneId.systemDefault() here
    
        ZonedDateTime zdtAtAsia = localDateTime.atZone(zoneId); // add zone information
    
        ZonedDateTime zdtAtET = zdtAtAsia
                .withZoneSameInstant(ZoneId.of("America/New_York")); // Same time in ET timezone
         
    

    就是这样!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多