package can.lyj.com;
public class Mycalander {
/**
*
* @param year
* 年份
* @return
*/
private static boolean isLoopYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
/**
*
* @param year
* 年份
* @return 获得当前日期的第一天是星期几
*/
private static int getWeek(int year, int month) {
long days = 0, sum = 0;
final int MAX = 366, MIN = 365, Day_OF_WEEK = 7;
for (int y = 1; y < year; y++) {
days = isLoopYear(y) ? MAX : MIN;
sum += days;
}
for (int mon = 1; mon < month; mon++) {
if (mon != 2) {
int dy = isBig(mon) ? 31 : 30;
sum += dy;
} else if (mon == 2) {
sum += isLoopYear(year) ? 29 : 28;
}
}
int week = (int) ((sum + 1) % Day_OF_WEEK);
return week;
}
/**
*
* @param month月份
* 判断是大月还是小月
*/
private static boolean isBig(int month) {
switch (month) {
case 1:case 3:case 5:case 7:case 8 : case 10 :case 12:
return true;
default:
return false;
}
}
private static int getHowDay(int currMonth, int year) {
if (currMonth == 2) {
if (isLoopYear(year)) {
return 29;
} else
return 28;
}
return isBig(currMonth) ? 31 : 30;
}
/**
* 根据年月获得日历数组
*
* @param years
* @param months
* @return
*/
public static int[][] getDateAry(int years, int months) {
int[][] date = new int[6][7];
int howDays = getHowDay(months, years);
final int before=getHowDay( months==1?12:months-1,months==1?years-1:years);
int howWeek = getWeek(years, months);
int first=before-howWeek+1;
int index = 0;
int priveous=1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7 ; j++) {
if (i == 0) {
if (j < howWeek) {
date[0][j]=first++;
} else {
date[0][j] = ++index;
}
} else if( index
date[i][j] = ++index;
}
else{
date[i][j]=priveous;
priveous++;
}
}
}
return date;
}
}