Java生成当月日历

tech2024-10-25  13

import java.time.DayOfWeek; import java.time.LocalDate; public class Demo02 { public static void main(String[] args) { LocalDate date = LocalDate.now(); //当前的年月日 int month = date.getMonthValue(); //获取当前月份 int day = date.getDayOfMonth(); //获取当前几号 date = date.minusDays(day - 1); //将date设置为当月第一天,minusDays()是减去指定天数 3-(3-1) DayOfWeek weekday = date.getDayOfWeek(); //得到这一天为星期几 // 1 = Monday 2=Tuesday..... 7 = Sunday int value = weekday.getValue(); System.out.println("Mon Tue Wed Thu Fri Sat Sun"); for (int i = 1; i < value; i++) { System.out.print(" "); } while (date.getMonthValue() == month) { //循环条件为当月 System.out.printf("%3d",date.getDayOfMonth()); //打印当前几号 if(date.getDayOfMonth() == day) { System.out.print("*"); //对今天进行标记 } else { System.out.print(" "); } date = date.plusDays(1); //天数 +1 if(date.getDayOfWeek().getValue() == 1) { //如果达到新周的第一天 System.out.println(); //换行 } } } } //以下为输出结果 /* Mon Tue Wed Thu Fri Sat Sun 1 2 3* 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Process finished with exit code 0 */
最新回复(0)