JAVA IO[2] 打印简单的日历

代码来源于JAVA 核心技术

import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class CalendarTest{

    public static void main(String[] args){
        //construct a current fate
        GregorianCalendar d = new GregorianCalendar();

        int today = d.get(Calendar.DAY_OF_MONTH);
        int month = d.get(Calendar.MONTH);

        //acquire indent
        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);
        }

        //output WEEKDAY
        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();

        //output Calendar
        for(int i = 0;i < indent;i++)
            System.out.print("    ");

        d.set(Calendar.DAY_OF_MONTH,1);
        do{
            //print day
            int day = d.get(Calendar.DAY_OF_MONTH);
            System.out.printf("%3d",day);

            //print * for today
            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(month == d.get(Calendar.MONTH));

        if(weekDay != firstDayOfWeek)
            System.out.println();

    }
}

小结:
在控制台环境时,输出中文星期时,对齐会出现问题,但是在IDE环境时则不会出现这种问题。
设置时区为:Locale.setDefault(Locale.US);
Locale.setDefault(Locale.CHINA);
Locale.setDefault(Locale.UK);

你可能感兴趣的:(JAVA)