写一个计算这个年里面里的每个月里面有多少天的工具类
以下是一个计算每个月份天数的工具类的示例代码:
import java.time.LocalDate;
import java.time.YearMonth;
public class MonthDaysCalculator {
public static int getDaysInMonth(int year, int month) {
YearMonth yearMonth = YearMonth.of(year, month);
return yearMonth.lengthOfMonth();
}
public static void main(String[] args) {
int year = 2022;
for (int month = 1; month <= 12; month++) {
int days = getDaysInMonth(year, month);
System.out.println(year + "年" + month + "月有" + days + "天");
}
}
}
使用YearMonth类可以方便地获取指定年份和月份的天数。在getDaysInMonth方法中,我们使用YearMonth.of(year, month)构造一个YearMonth对象,然后通过lengthOfMonth方法获取该月份的天数。
在main方法中,我们遍历每个月份,调用getDaysInMonth方法获取天数,并输出结果。
运行上述代码,可以得到类似以下的输出:
2022年1月有31天
2022年2月有28天
2022年3月有31天
2022年4月有30天
2022年5月有31天
2022年6月有30天
2022年7月有31天
2022年8月有31天
2022年9月有30天
2022年10月有31天
2022年11月有30天
2022年12月有31天
``
原文地址: https://www.cveoy.top/t/topic/iZ3K 著作权归作者所有。请勿转载和采集!