Java 8中如何用java.time API比较旧版java.util.Date与指定日期?
解决遗留java.util.Date与ISO日期字符串的范围判断问题
要仅使用Java 8+的java.time API完成需求,核心是将遗留的java.util.Date与ISO日期字符串统一转换为java.time体系下的类型,再进行比较。具体实现如下:
1. 转换遗留Date对象为LocalDate
java.util.Date本质是时间戳,先转为Instant,再通过指定时区转换为业务所需的LocalDate(时区需根据业务场景确定,示例使用系统默认时区,也可指定如ZoneOffset.UTC):
java.util.Date date = legacyService.retrieveLegacyDate(..); LocalDate targetDate = date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate();
2. 解析ISO日期字符串
直接用LocalDate.parse()方法解析标准ISO格式的日期字符串:
LocalDate startDate = LocalDate.parse("2022-08-16"); LocalDate endDate = LocalDate.parse("2022-10-17");
3. 执行范围判断
利用LocalDate提供的isAfter()和isBefore()方法完成边界判断,可根据业务需求调整是否包含边界:
// 严格判断日期在(2022-08-16, 2022-10-17)区间内 if (targetDate.isAfter(startDate) && targetDate.isBefore(endDate)) { // 日期符合要求,继续执行.... } // 若需包含起始日期,判断[2022-08-16, 2022-10-17)区间 if (!targetDate.isBefore(startDate) && targetDate.isBefore(endDate)) { // 日期符合要求,继续执行.... }
补充:精确到时间点的范围判断
如果业务要求判断时间戳是否落在ISO时间字符串的区间内(而非仅日期),可将Date转为Instant,同时解析ISO时间字符串为Instant后比较:
Instant targetInstant = date.toInstant(); Instant startInstant = Instant.parse("2022-08-16T00:00:00Z"); Instant endInstant = Instant.parse("2022-10-17T00:00:00Z"); if (targetInstant.isAfter(startInstant) && targetInstant.isBefore(endInstant)) { // 时间点符合要求,继续执行.... }
内容的提问来源于stack exchange,提问作者maxxyme
相关产品推荐
相关产品推荐

