公元元年一月一日为星期一
即 0001-01-01 是星期一
以今天为例,2017年8月26号
每个平年 365 天,52*7 + 1 = 365,就是说每过一个平年,同月同日是星期几递增一天,那从公元元年1月1日到现在经过了 2016年,增加 2016 天
而在这 1-2017 年度中,每隔四年多一个闰年多一天,共多 2016 除以 4 取整 504 天;
每隔 100 年少一个闰年,再减少 20 天;
每隔 400 年再多一个闰年,多 5 天
共 2016 + 504 - 20 + 5 这么多天
其实我们只要这个数字除以 7 的余数,就是 6
现在再算算今年过去的天数:
一月 31 天,除以 7 余 3
二月 28 天,除以 7 余 0
三月 31 天,除以 7 余 3
四月 30 天,除以 7 余 2
五月 31 天,除以 7 余 3
六月 30 天,除以 7 余 2
七月 31 天,除以 7 余 3
八月从 1 号到今天,25 天,除以 7 余 4 天
合计除以 7 余 5
因此从 0001-1-1 到 2017-8-26 共经过若干星期外加 1 天,今天星期六,可见公元元年1月1日是星期一
代码:
/*
* This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
*/
void GregorianDay(TimeTypeDef * tm)
{
int leapsToDate;
int lastYear;
int currentYear;
int day;
int MonthOffset[] = { 0,31,59,90,120,151,181,212,243,273,304,334 };
lastYear=tm->Year+2000-1;
currentYear = tm->Year+2000;
/*
* Number of leap corrections to apply up to end of last year
*/
leapsToDate = lastYear/4 - lastYear/100 + lastYear/400;
/*
* This year is a leap year if it is divisible by 4 except when it is
* divisible by 100 unless it is divisible by 400
*
* e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 will be
*/
if((currentYear%4==0) &&
((currentYear%100!=0) || (currentYear%400==0)) &&
(tm->Month>2)) {
/*
* We are past Feb. 29 in a leap year
*/
day=1;
} else {
day=0;
}
day += lastYear*365 + leapsToDate + MonthOffset[tm->Month-1] + tm->Day;
tm->Week=day%7;
}