Last active
December 22, 2015 11:40
-
-
Save syhily/4c420f525420e89d112f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.*; | |
| public class CalendarUtils { | |
| private static final String[] weekTitle = {"一", "二", "三", "四", "五", "六", "日"}; | |
| private static final String[] monthTitle = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"}; | |
| private static final int[] monthSize = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; | |
| private CalendarUtils() { | |
| // No Construct function | |
| } | |
| /** | |
| * 主方法 | |
| */ | |
| public static void getCalendar(final int year) { | |
| for (int month = 0; month < monthTitle.length; month++) { | |
| printMonthtitle(monthTitle[month]); | |
| printMonthBody(year, month + 1); | |
| } | |
| } | |
| /** | |
| * 是不是闰年 | |
| */ | |
| private static boolean isLeapYear(final int year) { | |
| return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0; | |
| } | |
| /** | |
| * 循环打印月标题 | |
| */ | |
| private static void printMonthtitle(final String monthTitle) { | |
| System.out.println(" " + monthTitle); | |
| } | |
| /** | |
| * 循环打印月日历 | |
| */ | |
| private static void printMonthBody(final int year, final int month) { | |
| printWeekTitle(); | |
| for (int i = 0; i < (getMonthSize(year, month) + getStartOffset(year, month)); i++) { | |
| if (i < getStartOffset(year, month)) { | |
| System.out.print("\t"); | |
| } else { | |
| System.out.print(i + 1 - getStartOffset(year, month)); | |
| if ((i + 1) % 7 == 0) { | |
| System.out.print("\n"); | |
| } else { | |
| System.out.print("\t"); | |
| } | |
| } | |
| } | |
| System.out.println("\n"); | |
| } | |
| /** | |
| * 循环打印周标题 | |
| */ | |
| private static void printWeekTitle() { | |
| for (int i = 0; i < weekTitle.length; i++) { | |
| System.out.print(weekTitle[i] + (i == 6 ? "\n": "\t")); | |
| } | |
| } | |
| /** | |
| * 获取这个月的天数 | |
| */ | |
| private static int getMonthSize(final int year, final int month) { | |
| return (isLeapYear(year) && month == 2) ? 29 : monthSize[month - 1]; | |
| } | |
| /** | |
| * 获取这个月第一天的开始周 蔡勒(zeller)公式 | |
| */ | |
| private static int getStartOffset(int year, int month) { | |
| int week = 0; | |
| if (month < 3) { | |
| month += 12; | |
| year--; | |
| } | |
| int century = year / 100; | |
| year = year % 100; | |
| week = year + year / 4 + century / 4 - 2 * century + (26 * (month + 1))/ 10; | |
| week = week % 7; | |
| return week == 0 ? 6 : week - 1; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment