Step By Step(Java 常用对象篇<二>)
1. Calendar:
对于每一个Java的开发者而言,这是一个再熟悉不过的对象了,这里我们给出一个巧妙的例子,至于如何巧妙,看了输出结果就清楚了。
1 public class MyTest {
2 public static void main(String args[]) {
3 GregorianCalendar d = new GregorianCalendar();
4 int today = d.get(Calendar.DAY_OF_MONTH);
5 int month = d.get(Calendar.MONTH);
6 // set d to the first date of the month
7 d.set(Calendar.DAY_OF_MONTH, 1);
8 int weekday = d.get(Calendar.DAY_OF_WEEK);
9 // get first day of week(Sunday in the U.S.)
10 int firstDayOfWeek = d.getFirstDayOfWeek();
11 // determine the required indentation for the first line
12 int indent = 0;
13 while (weekday != firstDayOfWeek) {
14 ++indent;
15 d.add(Calendar.DAY_OF_MONTH, -1);
16 weekday = d.get(Calendar.DAY_OF_WEEK);
17 }
18 // print weekday names
19 String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
20 do {
21 System.out.printf("%4s", weekdayNames[weekday]);
22 d.add(Calendar.DAY_OF_MONTH, 1);
23 weekday = d.get(Calendar.DAY_OF_WEEK);
24 } while (weekday != firstDayOfWeek);
25 System.out.println();
26
27 for (int i = 1; i <= indent; ++i)
28 System.out.print(" ");
29
30 d.set(Calendar.DAY_OF_MONTH, 1);
31 do {
32 // print day
33 int day = d.get(Calendar.DAY_OF_MONTH);
34 System.out.printf("%5d", day);
35 // mark current day with *
36 if (day == today)
37 System.out.print("*");
38 else
39 System.out.print(" ");
40 // advance d to the next day
41 d.add(Calendar.DAY_OF_MONTH, 1);
42 weekday = d.get(Calendar.DAY_OF_WEEK);
43 // start a new line at the start of the week
44 if (weekday == firstDayOfWeek)
45 System.out.println();
46 } while (d.get(Calendar.MONTH) == month);
47 // the loop exists when d is day 1 of the next month
48
49 // print final end of line if neccessary
50 if (weekday != firstDayOfWeek)
51 System.out.println();
52 }
53 }
54 /* 输出结果如下:
55 星期日 星期一 星期二 星期三 星期四 星期五 星期六
56 1 2 3
57 4 5 6 7* 8 9 10
58 11 12 13 14 15 16 17
59 18 19 20 21 22 23 24
60 25 26 27 28 29 30
61 */
复制代码
2. java
补充:软件开发 , Java ,