ChronoUnit.DAYS. Between 返回两个 java.time.LocalDate 对象之间的错误天数

问题描述 投票:0回答:2
public static long getDaysBetween(Record record) {
  if (record == null || record.getRecordedDate() == null) {
   throw new RuntimeException("Unable to extract update date from record");
 }

 LocalDate date = record.getRecordedDate().toLocalDateTime().toLocalDate();
 return ChronoUnit.DAYS.between(date, LocalDate.now());
}

如果记录 getRecordedDate() 是“2023-11-01”,它应该返回 2023 年 11 月 1 日到今天(2024 年 3 月 19 日)之间的天数,但是,我得到的是 181!

从那时到现在的天数总是相差几个月,因为它将“2023-11-01”解释为“现在 - 181 天”(如 9 月)

Record.getRecordedDate() 返回 java.sql.Timestamp,我将其转换为 java.time.LocalDate。

我做错了什么?

所有 joda-time 类库对我们来说都是禁区,大多数非 Java 核心库也是如此,所以 java.time 是我在这里只能使用的。

谢谢

java java-time
2个回答
0
投票

返回java.sql.Timestamp

该类是存在严重缺陷的遗留日期时间类之一。如果可能的话,首先避免使用它。迁移为仅使用 java.time 类。

如果收到

java.sql.Timestamp
,请立即转换为替代品,
java.time.Instant

Instant instant = myJavaSqlTimestamp.toInstant() ;

Instant
类代表一个时刻,即时间线上的一个点,与 UTC 的偏移量为零小时-分钟-秒。

要从某个时刻导出一天,您必须指定时区。对于任何给定时刻,全球各地的日期因时区而异。在日本东京,某个时刻可能是“明天”,而在美国俄亥俄州托莱多,某个时刻可能是“昨天”。

ZoneId z = ZoneId.of( "America/Edmonton" ) ; ZonedDateTime zdt = instant.atZone( z ) ;

instant

zdt
都代表同一时刻,时间轴上同一同时点,但通过两个不同的时钟/日历看到。

提取日期部分。

LocalDate ld = zdt.toLocalDate() ;
    

0
投票
在做了一些进一步的研究之后,遍历每个 Record 对象的循环以某种方式提取了错误的 Record 对象,因此,得到了错误的 Record getRecordedDate(),并且修复后,该方法在正确的 Record 之间的天数内按预期工作getRecordedDate() 和现在

© www.soinside.com 2019 - 2024. All rights reserved.