本文實例講述了Java實現按年月打印日曆功能。分享給大家供大家參考,具體如下:
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; // 格式化月份,因為要轉成yyyyMMdd格式的if (month < 10) { monthStr = "0" + month; } else { monthStr = month + ""; // 數字跟字符串拼接轉成字符串格式} String yearMonthStr = year + monthStr; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Calendar calendarEnd = Calendar.getInstance(); Calendar calendarStart = Calendar.getInstance(); // 根據年份和月份得到輸入月份有多少天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); // 得到當月第一天是星期幾,這裡週日為第一天,從1開始,週一則為2 int dayOfWeek = calendarStart.get(Calendar.DAY_OF_WEEK); int day = 1; // 當月的第一周做特殊處理,單獨打印一行for (int i = 1; i <= 7; i++) { if (i >= dayOfWeek) { System.out.print(" " + day + " "); day++; } else { System.out.print(" "); } } System.out.println(); // 開始打印從第二週開始的日期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("日" + " " + "一" + " " + "二" + " " + "三" + " " + "四" + " " + "五" + " " + "六"); }}運行結果截圖(運行效果,字體大小5號最佳):
PS:這裡再為大家推薦幾款關於日期與時間計算的在線工具供大家參考使用:
在線日期/天數計算器:
http://tools.VeVB.COm/jisuanqi/date_jisuanqi
在線萬年曆日曆:
http://tools.VeVB.COm/bianmin/wannianli
在線陰曆/陽曆轉換工具:
http://tools.VeVB.COm/bianmin/yinli2yangli
Unix時間戳(timestamp)轉換工具:
http://tools.VeVB.COm/code/unixtime
更多關於java相關內容感興趣的讀者可查看本站專題:《java日期與時間操作技巧匯總》、《Java數據結構與算法教程》、《Java操作DOM節點技巧總結》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。