You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

java.time包中是否有等效于DateTime.dayOfYear().isLeap()的闰日判断方法?

等效的java.time闰日判断方法

在Java 8+的java.time包中,没有和Joda-Time里date.dayOfYear().isLeap()完全对应的直接方法,但可以通过结合闰年判断+日期校验实现等效逻辑,且完全符合ISO 8601公历规则——无需担心硬编码的合理性,因为闰日的定义就是公历闰年的2月29日。

基础实现代码

import java.time.LocalDate;

// 假设已有LocalDate实例(若原代码用带时区的DateTime,可先转成LocalDate)
LocalDate date;
// 判断是否为闰日
return date.isLeapYear() && date.getMonthValue() == 2 && date.getDayOfMonth() == 29;

增强可读性的写法

借助Month枚举类替代数字,提升代码可维护性:

import java.time.LocalDate;
import java.time.Month;

LocalDate date;
return date.isLeapYear() && date.getMonth() == Month.FEBRUARY && date.getDayOfMonth() == 29;

时区适配说明

如果原代码使用带时区的DateTime,可先将其转换为对应时区的LocalDate(国际业务场景下,需确保时区转换符合业务逻辑):

// 示例:从带时区的ZonedDateTime转LocalDate
ZonedDateTime zonedDateTime;
LocalDate date = zonedDateTime.toLocalDate();

内容的提问来源于stack exchange,提问作者Kirby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 07:45:55