Skip to content

Instantly share code, notes, and snippets.

@qsona
Last active August 29, 2015 13:59
Show Gist options
  • Save qsona/10652643 to your computer and use it in GitHub Desktop.
Save qsona/10652643 to your computer and use it in GitHub Desktop.
package calendar;
public class Calendar {
public static final int[] DAY_NUMS = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public static final String[] Days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
public static final int BASIS_YEAR = 2014;
public static final int BASIS_JAN_1ST_DAY_INDEX = 3; // Wed
public void print(int year, int month) {
if (month <= 0 || 13 <= month) {
throw new IllegalArgumentException();
}
final int firstDayIndex = this.getFirstDayIndex(year, month);
final int dayNum = this.getDayNum(year, month);
String line1 = "", line2 = "";
int dayIndex = firstDayIndex;
for (int day = 1; day <= dayNum; day++) {
line1 += Days[dayIndex];
if (day <= 9) {
line2 += " " + day;
} else {
line2 += " " + day;
}
dayIndex = (dayIndex + 1) % Days.length;
if (day % 7 == 0 || day == dayNum) {
System.out.println(line1);
System.out.println(line2);
line1 = "";
line2 = "";
} else {
line1 += " ";
line2 += " ";
}
}
}
private boolean isUruudoshi(int year) {
if (year % 4 != 0) {
return false;
}
if (year % 100 == 0 && year % 400 != 0) {
return false;
}
return true;
}
private int getDayNum(int year, int month) {
if (month == 2) {
return isUruudoshi(year) ? 29 : 28;
}
return DAY_NUMS[month - 1];
}
private int getFirstDayIndex(final int year, final int month) {
// 2800年周期
int diffYear = (year - BASIS_YEAR) % 2800;
if (diffYear < 0) {
diffYear += 2800;
}
// クソ効率悪い
int dayIndex = BASIS_JAN_1ST_DAY_INDEX;
for (int i = 0; i < diffYear; i++) {
if (isUruudoshi(BASIS_YEAR + i)) {
dayIndex += 2;
} else {
dayIndex += 1;
}
dayIndex %= 7;
}
for (int i = 1; i <= month - 1; i++) {
dayIndex += this.getDayNum(year, i);
}
dayIndex %= 7;
return dayIndex;
}
public static void main(String[] args) {
Calendar c = new Calendar();
c.print(2017, 2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment