在 java 日期时间 api 中,yearmonth 和 monthday 分别用于处理“年-月”组合与“月-日”组合。yearmonth 适用于需要跨年度但忽略具体日期的场景,如账单周期;monthday 适用于每年重复的周期性事件,如生日或纪念日。两者均不可变且线程安全,通过静态工厂方法创建,并支持丰富的格式化与计算功能。

YearMonth 如何表示和处理年月数据
YearMonth 通过 of() 静态方法创建,提供 lengthOfMonth()、atEndOfMonth() 等方法获取当月信息,并支持月份加减操作。它常用于财务结算、订阅管理等场景。

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class YearMonthDemo {
public static void main(String[] args) {
// 创建 YearMonth 对象
YearMonth ym = YearMonth.of(2024, 2);
// 获取当月天数
int daysInMonth = ym.lengthOfMonth();
System.out.println("2024年2月有 " + daysInMonth + " 天");
// 获取月末日期
var lastDay = ym.atEndOfMonth();
System.out.println("月末日期: " + lastDay);
// 月份加减
YearMonth nextMonth = ym.plusMonths(1);
System.out.println("下个月: " + nextMonth);
// 格式化输出
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
System.out.println("格式化: " + ym.format(formatter));
}
}
MonthDay 如何表示和处理月日数据
MonthDay 同样使用 of() 创建,代表一年中的某月某日,不包含年份。它适合处理每年重复的事件,如生日、纪念日等。可通过 isValidYear() 验证特定年份是否有效(如闰年2月29日)。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
立即学习“Java免费学习笔记(深入)”;

import java.time.MonthDay;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class MonthDayDemo {
public static void main(String[] args) {
// 创建 MonthDay 对象(2月29日,闰年才有效)
MonthDay md = MonthDay.of(2, 29);
// 验证2024年是否有效(2024是闰年)
boolean isValid2024 = md.isValidYear(2024);
System.out.println("2024年2月29日有效: " + isValid2024);
// 验证2023年是否有效(2023不是闰年)
boolean isValid2023 = md.isValidYear(2023);
System.out.println("2023年2月29日有效: " + isValid2023);
// 结合当前年份生成完整日期
MonthDay birthday = MonthDay.of(5, 15);
LocalDate thisYearBirthday = birthday.atYear(LocalDate.now().getYear());
System.out.println("今年的生日: " + thisYearBirthday);
// 格式化输出
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
System.out.println("格式化: " + birthday.format(formatter));
}
}
YearMonth 和 MonthDay 在闰年处理上的差异是什么
YearMonth 自动处理闰年逻辑,lengthOfMonth() 会返回正确的天数(平年28天,闰年29天)。而 MonthDay 本身不包含年份,需通过 isValidYear() 显式验证特定年份的有效性。例如,2月29日在闰年有效,在非闰年无效。这种设计使 MonthDay 更适合处理固定月日的重复事件,而 YearMonth 更适合需要精确月份长度的场景。

















