カレンダー印刷

1916 ワード

具体的なコードは以下の通りです.

package com.chapterOne.exercise;

import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * Created by yangjianzhou on 2014/8/15 14:30.
 * TODO :
 */
public class CalendarTest {

    public static void main(String[] args) {

        GregorianCalendar currentDate = new GregorianCalendar();
        int today = currentDate.get(Calendar.DAY_OF_MONTH);
        int month = currentDate.get(Calendar.MONTH);

        currentDate.set(Calendar.DAY_OF_MONTH, 1);
        int weekday = currentDate.get(Calendar.DAY_OF_WEEK);
        System.out.println("Sun Mon Tue Wed Thu Fri Sat");
        for (int i = Calendar.SUNDAY; i < weekday; i++) {
            System.out.print("\t");
        }
        do {
            int day = currentDate.get(Calendar.DAY_OF_MONTH);
            System.out.printf("%3d", day);
            if (day == today) {
                System.out.print("* ");
            } else {
                System.out.print(" ");
            }
            if (weekday == Calendar.SATURDAY) {
                System.out.println();
            }

            currentDate.add(Calendar.DAY_OF_MONTH, 1);
            weekday = currentDate.get(Calendar.DAY_OF_WEEK);
        } while (currentDate.get(Calendar.MONTH) == month);
        if (weekday != Calendar.SUNDAY) {
            System.out.println();
        }
    }
}


実行結果は次のとおりです.

Sun Mon Tue Wed Thu Fri Sat
					  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 
 31