需求:使用GregorianCalendar对象获取日期信息,在控制台显示本月日历。
效果:
July
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
结果中带有"*"号的日期代表当前日期。
代码:
package gemu.test.date;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* 控制台显示本月日历
* @author Gemu
* @date 2015-7-3
*/
public class GregorianCalendarTest {
public static void main(String[] args) {
GregorianCalendar now = new GregorianCalendar(); // 当前日期
int today = now.get(Calendar.DAY_OF_MONTH); // 获取当前日期是本月的第几天
int month = now.get(Calendar.MONTH);
now.set(Calendar.DAY_OF_MONTH, 1); // 设置当前日期是本月的第1天
int weekday = now.get(Calendar.DAY_OF_WEEK); // 获取当前日期所在的周有几天
int firstDayOfWeek = now.getFirstDayOfWeek();
int indent = 0;
while (weekday != firstDayOfWeek) {
indent++ ;
now.add(Calendar.DAY_OF_MONTH, -1); // 将当前日期的前一天是本月的第几天设置为当前日期所在本月的第几天。哎~这个真的不知道怎么解释了=.=!
weekday = now.get(Calendar.DAY_OF_WEEK);
}
String[] weekdayNames = new DateFormatSymbols(Locale.US).getShortWeekdays();
String[] months = new DateFormatSymbols(Locale.US).getMonths();
System.out.println(months[month]);
do {
System.out.printf("%4s", weekdayNames[weekday]);
now.add(Calendar.DAY_OF_MONTH, 1);
weekday = now.get(Calendar.DAY_OF_WEEK);
} while (weekday != firstDayOfWeek);
System.out.println();
for (int i = 1; i <= indent; i++) {
System.out.printf(" ");
}
now.set(Calendar.DAY_OF_MONTH, 1); // 将当前日期的后一天是本月的第几天设置为当前日期所在本月的第几天。还是不要看这行注释了。。。=.=!
do {
int day = now.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d", day);
if (day == today)
System.out.print("*");
else
System.out.print(" ");
now.add(Calendar.DAY_OF_MONTH, 1);
weekday = now.get(Calendar.DAY_OF_WEEK);
if (weekday == firstDayOfWeek)
System.out.println();
} while (now.get(Calendar.MONTH) == month);
if (weekday != firstDayOfWeek)
System.out.println();
}
}