Java如何计算每个自然月的天数并打印出日期
时间: 2024-05-04 21:22:52 浏览: 132
Java中可以使用Java.time包中的YearMonth类来计算每个自然月的天数,并使用LocalDate类来打印出日期。具体代码如下:
```
import java.time.LocalDate;
import java.time.YearMonth;
public class Main {
public static void main(String[] args) {
//指定年月
YearMonth yearMonth = YearMonth.of(2022, 3);
//获取这个月的天数
int daysInMonth = yearMonth.lengthOfMonth();
System.out.println("这个月有" + daysInMonth + "天");
//打印出日期
for (int day = 1; day <= daysInMonth; day++) {
LocalDate date = yearMonth.atDay(day);
System.out.println(date);
}
}
}
```
该代码会输出:
```
这个月有31天
2022-03-01
2022-03-02
2022-03-03
2022-03-04
2022-03-05
2022-03-06
2022-03-07
2022-03-08
2022-03-09
2022-03-10
2022-03-11
2022-03-12
2022-03-13
2022-03-14
2022-03-15
2022-03-16
2022-03-17
2022-03-18
2022-03-19
2022-03-20
2022-03-21
2022-03-22
2022-03-23
2022-03-24
2022-03-25
2022-03-26
2022-03-27
2022-03-28
2022-03-29
2022-03-30
2022-03-31
```
阅读全文