import java.text.DateFormatSymbols;
import java.util.*;
/**
* @version 1.4 2007-04-07
* @author Cay Horstmann
*/
public class CalendarTest
{
public static void main(String[] args)
{
// construct d as current date
Locale.setDefault(Locale.US);
GregorianCalendar d = new GregorianCalendar();
int today = d.get(Calendar.DAY_OF_MONTH);
int month = d.get(Calendar.MONTH);
// System.out.println("today is :"+today);
// System.out.println("month is :"+month);//注意:month从0开始计算的,即一月份对应0
// set d to start date of the month
d.set(Calendar.DAY_OF_MONTH, 1);
//设置d为当前的第一天
int weekday = d.get(Calendar.DAY_OF_WEEK);
//获得当前第一天所对应的星期几
// get first day of week (Sunday in the U.S.)
int firstDayOfWeek = d.getFirstDayOfWeek();
//获得当前地区星期的起始日
// determine the required indentation for the first line
int indent = 0;
while (weekday != firstDayOfWeek)
{
indent++;
d.add(Calendar.DAY_OF_MONTH, -1);
//将当前日历对象的日减少1,直到一个星期的第一天为止
weekday = d.get(Calendar.DAY_OF_WEEK);
}
// print weekday names
String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
do
{
//此时d指向一周的第一天即对应sunday的日子,所以下面第一句输出地weekdayNames对应为sunday
System.out.printf("%4s", weekdayNames[weekday]);
//此时d指向下一天即对应monday的日子
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(" ");
//the end of the print of the xingqiji
d.set(Calendar.DAY_OF_MONTH, 1); //d指向本月第一天
do //程序开始正式打印日期
{
// print day
int day = d.get(Calendar.DAY_OF_MONTH); //获得本月第一天的日期并且打印
System.out.printf("%3d", day);
// mark current day with *
if (day == today) System.out.print("*"); //如果打印到了今天那么就在day后添加*
else System.out.print(" ");//如果打印到了不是今天那么就在day后什么都不添加只打印日期号码
// advance d to the next day
d.add(Calendar.DAY_OF_MONTH, 1);//将d指向下一天
weekday = d.get(Calendar.DAY_OF_WEEK);//获得下一天的星期数
// start a new line at the start of the week
if (weekday == firstDayOfWeek) System.out.println();
}
while (d.get(Calendar.MONTH) == month);//当d不再指向本月时候跳出循环
// the loop exits when d is day 1 of the next month
// print final end of line if necessary
if (weekday != firstDayOfWeek) 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
三、调试过程中遇到的问题
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
如上所示:对应的错误原因:
for (int i = 1; i <= indent; i++)
System.out.print("");
由于System.out.printf("%4s", weekdayNames[weekday]);中对应定义了每一个为4个字符的长度,对应print输出地字符串中没有空出4个空格,进行正确的移位
修改方法:
for (int i = 1; i <= indent; i++)
System.out.print(" ");
从而可以实现最终的调试结果