java 根据年月获取日历
时间: 2023-08-10 21:02:12 浏览: 61
你可以使用 Java 中的 `Calendar` 类来获取指定年月的日历。以下是一个示例代码:
```java
import java.util.Calendar;
public class CalendarExample {
public static void main(String[] args) {
int year = 2022;
int month = 1; // January (0 - 11)
// Create a Calendar instance
Calendar calendar = Calendar.getInstance();
// Set the year and month
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
// Get the number of days in the month
int numDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
// Print the calendar
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
// Set the calendar to the first day of the month
calendar.set(Calendar.DAY_OF_MONTH, 1);
// Print the first week of the month
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
for (int i = 0; i < dayOfWeek; i++) {
System.out.print(" ");
}
for (int i = 1; i <= 7 - dayOfWeek; i++) {
System.out.printf("%3d ", i);
}
System.out.println();
// Print the remaining weeks of the month
for (int i = 7 - dayOfWeek + 1; i <= numDays; i++) {
System.out.printf("%3d ", i);
if ((i + dayOfWeek - 1) % 7 == 0) {
System.out.println();
}
}
}
}
```
在此示例中,我们使用 `Calendar.getInstance()` 方法创建了一个 `Calendar` 实例。然后,我们设置了年份和月份,并使用 `getActualMaximum()` 方法获取了该月的天数。接下来,我们打印了日历的表头,然后将日历设置为该月的第一天,并打印了第一周。最后,我们打印了剩余的周。