在java控制台打印日历

public static void main(String[] args) {
    
    Locale.setDefault(Locale.ENGLISH);
    GregorianCalendar d = new GregorianCalendar();
    //现在是当前月份的第几天
    int today = d.get(Calendar.DAY_OF_MONTH);
    //现在是几月份
    int month = d.get(Calendar.MONTH);
    //设置当前时间为这个月的第一天
    d.set(Calendar.DAY_OF_MONTH, 1);
    //月份第一天是星期几
    int weekday = d.get(Calendar.DAY_OF_WEEK);
    //获取一星期的第一天
    int firstDayOfWeek = d.getFirstDayOfWeek();
    int indent = 0;
    //如果月份的第一个天不是一个星期的第一天,要知道空几个空格,并把当前时间设置到一星期的第一天
    while (weekday != firstDayOfWeek) {
      indent++;
      d.add(Calendar.DAY_OF_MONTH, -1);
      weekday = d.get(Calendar.DAY_OF_WEEK);
    }

    //打印星期头
    String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
    do {
      System.out.printf("%4s", weekdayNames[weekday]);
      d.add(Calendar.DAY_OF_MONTH, 1);
      weekday = d.get(Calendar.DAY_OF_WEEK);
    }
    while (weekday != firstDayOfWeek);
    System.out.println();
    for (int i = 1; i <= indent; i++) {
      System.out.print("    ");
    }
    //设置当前时间为月初
    d.set(Calendar.DAY_OF_MONTH, 1);
    do {
      //打印天数
      int day = d.get(Calendar.DAY_OF_MONTH);
      System.out.printf("%3d", day);

      //标准当前日期
      if (day == today) {
        System.out.print("*");
      } else {
        System.out.print(" ");
      }
      d.add(Calendar.DAY_OF_MONTH, 1);
      weekday = d.get(Calendar.DAY_OF_WEEK);

      //到日期第一天,换行
      if (weekday == firstDayOfWeek){
        System.out.println();
      }
    }
    while (d.get(Calendar.MONTH) == month);
    //最后是否需要换行
    if (weekday != firstDayOfWeek){
      System.out.println();
    }
  }

你可能感兴趣的:(Java技术)