用Java输出上一个月日历
时间: 2023-12-07 07:04:30 浏览: 90
Java输出月份日历
以下是Java代码示例,用于输出上一个月的日历:
```
import java.time.LocalDate;
import java.time.Month;
public class LastMonthCalendar {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
int currentYear = currentDate.getYear();
Month currentMonth = currentDate.getMonth();
int lastMonthLength = currentMonth.minLength();
LocalDate lastMonthDate = LocalDate.of(currentYear, currentMonth.minus(1), 1);
int lastMonthStartDay = lastMonthDate.getDayOfWeek().getValue();
System.out.println(currentMonth + " " + currentYear);
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
for (int i = 1; i < lastMonthStartDay; i++) {
System.out.print(" ");
}
for (int i = 1; i <= lastMonthLength; i++) {
if (i < 10) {
System.out.print(" ");
}
System.out.print(i + " ");
if ((lastMonthStartDay + i - 1) % 7 == 0) {
System.out.println();
}
}
}
}
```
该程序使用Java 8的时间API,获取当前日期并计算上个月的第一天和天数。然后,使用上个月的第一天的星期几来确定日历表格中第一行的间距,以及在循环中打印日历的每个日期。
阅读全文