使用 java.time 包中的 yearmonth 类调用 lengthofmonth() 方法即可获取指定月份的天数。只需传入年份和月份构建对象,该方法会自动处理闰年等逻辑并返回对应的天数。

YearMonth.of(2024, 2) 会返回多少天
对于 2024 年 2 月,lengthOfMonth() 返回 29。因为 2024 是闰年,二月有 29 天。

import java.time.YearMonth;
public class Main {
public static void main(String[] args) {
YearMonth ym = YearMonth.of(2024, 2);
int days = ym.lengthOfMonth();
System.out.println(days); // 输出: 29
}
}
YearMonth.of(2023, 2) 会返回多少天
对于 2023 年 2 月,lengthOfMonth() 返回 28。因为 2023 不是闰年,二月只有 28 天。
立即学习“Java免费学习笔记(深入)”;

import java.time.YearMonth;
public class Main {
public static void main(String[] args) {
YearMonth ym = YearMonth.of(2023, 2);
int days = ym.lengthOfMonth();
System.out.println(days); // 输出: 28
}
}
如果输入非法月份如 13 会发生什么
如果传入的月份超出 1-12 范围,例如 13,YearMonth.of() 会抛出 DateTimeException 异常。程序必须捕获该异常或确保输入合法,否则运行时会中断。


















