本文實(shí)例講述了Java實(shí)現(xiàn)按年月打印日歷功能。分享給大家供大家參考,具體如下:
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
79
|
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class CalendarBook { public static void main(String[] args) throws ParseException { CalendarBook cb = new CalendarBook(); cb.printWeekTitle(); cb.printCalendar( 2018 , 3 ); } public void printCalendar( int year, int month) throws ParseException { String monthStr; // 格式化月份,因?yàn)橐D(zhuǎn)成yyyyMMdd格式的 if (month < 10 ) { monthStr = "0" + month; } else { monthStr = month + "" ; // 數(shù)字跟字符串拼接轉(zhuǎn)成字符串格式 } String yearMonthStr = year + monthStr; SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMdd" ); Calendar calendarEnd = Calendar.getInstance(); Calendar calendarStart = Calendar.getInstance(); // 根據(jù)年份和月份得到輸入月份有多少天 int monthDays = getMonthLastDay(year, month); // 月初的date字符串 String dateStartStr = yearMonthStr + "01" ; // 月末的date字符串 String dateEndStr = yearMonthStr + monthDays; Date startDate = sdf.parse(dateStartStr); Date endDate = sdf.parse(dateEndStr); calendarStart.setTime(startDate); calendarEnd.setTime(endDate); // 得到輸入月份有多少周 int weeks = calendarEnd.get(Calendar.WEEK_OF_MONTH); // 得到當(dāng)月第一天是星期幾,這里周日為第一天,從1開(kāi)始,周一則為2 int dayOfWeek = calendarStart.get(Calendar.DAY_OF_WEEK); int day = 1 ; // 當(dāng)月的第一周做特殊處理,單獨(dú)打印一行 for ( int i = 1 ; i <= 7 ; i++) { if (i >= dayOfWeek) { System.out.print( " " + day + " " ); day++; } else { System.out.print( " " ); } } System.out.println(); // 開(kāi)始打印從第二周開(kāi)始的日期 for ( int week = 1 ; week < weeks; week++) { for ( int i = 1 ; i <= 7 ; i++) { if (day > monthDays) { break ; } if (day < 10 ) { System.out.print( " " + day + " " ); } else { System.out.print(day + " " ); } day++; } System.out.println(); } } public int getMonthLastDay( int year, int month) { int monthDay; int [][] day = { { 0 , 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 }, { 0 , 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } }; if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ) { // 閏年 monthDay = day[ 1 ][month]; } else { monthDay = day[ 0 ][month]; } return monthDay; } public void printWeekTitle() { System.out.println( "日" + " " + "一" + " " + "二" + " " + "三" + " " + "四" + " " + "五" + " " + "六" ); } } |
運(yùn)行結(jié)果截圖(運(yùn)行效果,字體大小5號(hào)最佳):
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
原文鏈接:http://blog.csdn.net/lizonghuan/article/details/50172763