-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalendarExercise.java
More file actions
78 lines (65 loc) · 1.76 KB
/
CalendarExercise.java
File metadata and controls
78 lines (65 loc) · 1.76 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package Chapter4;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
/*
* 2017/1/16
* 输出当前月份的日历
* */
public class CalendarExercise {
public void getCalendar(){
//对象构造时的年月日
GregorianCalendar d=new GregorianCalendar();
System.out.println("现在是"+d.get(Calendar.YEAR)+"/"+d.get(Calendar.MONTH)+1+"/"+d.get(Calendar.DAY_OF_MONTH));
int today=d.get(Calendar.DAY_OF_MONTH);
int month=d.get(Calendar.MONTH);
//将d设置为这个月的第一天
d.set(Calendar.DAY_OF_MONTH,1);
//得到这一天是星期几
int weekday=d.get(Calendar.DAY_OF_WEEK);
//设置不同地区的显示
Locale.setDefault(Locale.US);
//得到当前地区星期一的起始日
int firstDayOfWeek=d.getFirstDayOfWeek();
int intent=0;
while(weekday!=firstDayOfWeek){
intent++;
d.add(Calendar.DAY_OF_MONTH, -1);
weekday=d.get(Calendar.DAY_OF_WEEK);
}
//输出表示星期几名称的前几个字母
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();
//打印空格
for(int i=0;i<intent;i++){
System.out.println(" ");
}
d.set(Calendar.DAY_OF_MONTH,1);
//输出日期
do{
int day=d.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d",day);
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(d.get(Calendar.MONTH)==month);
if(weekday!=firstDayOfWeek){
System.out.println();
}
}
}