主题: 读取系统时间并判断周几(判断周几使用基姆拉尔森计算公式)

{% meting "2111364820" "tencent" "playlist" "theme:#FF4081" "mode:circulation" "mutex:true" "listmaxheight:200px" "preload:auto" "autoplay" %}

$$
W= (d+2m+3(m+1)/5+y+y/4-y/100+y/400) mod 7
$$

1.其中d表示day 日期 m表示month 月份 y表示year 年

2.mod表示取余

3.关于时间是如何获取的:方法在代码块的注释中

代码实现如下

#include"stdio.h"
#include<time.h>

const char *getWeekdayByYearday(int iY, int iM, int iD)
{
	int iWeekDay = -1;
	if (1 == iM || 2 == iM)
	{
		iM += 12;
		iY--;
	}
	iWeekDay = (iD + 1 + 2 * iM + 3 * (iM + 1) / 5 + iY + iY / 4 - iY / 100 + iY / 400) % 7;
	switch (iWeekDay)
	{
	case 0: return "周日"; break;
	case 1: return "周一"; break;
	case 2: return "周二"; break;
	case 3: return "周三"; break;
	case 4: return "周四"; break;
	case 5: return "周五"; break;
	case 6: return "周六"; break;
	default: return NULL; break;
	}

	return NULL;
}

int main()
{
	time_t timep;
	struct tm * p;
	time(&timep);
	p = gmtime(&timep);
	//printf("%d\n", p->tm_sec); /*获取当前秒*/
	//printf("%d\n", p->tm_min); /*获取当前分*/
	//printf("%d\n", 8 + p->tm_hour);/*获取当前时,这里获取西方的时间,刚好相差八个小时*/
	//printf("%d\n", p->tm_mday);/*获取当前月份日数,范围是1-31*/
	//printf("%d\n", 1 + p->tm_mon);/*获取当前月份,范围是0-11,所以要加1*/
	//printf("%d\n", 1900 + p->tm_year);/*获取当前年份,从1900开始,所以要加1900*/
	//printf("%d\n", p->tm_yday); /*从今年1月1日算起至今的天数,范围为0-365*/
	

	printf("%d年%d月%d日%d时%d分%d秒,是今年的第%d天.\n", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday, 8 + p->tm_hour, p->tm_min, p->tm_sec,  p->tm_yday);/*获取当前年份,从1900开始,所以要加1900*/
	
//W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) % 7

	const char *t = getWeekdayByYearday(1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday);
	printf("今天是  : %s\n", t);
	getchar();
	printf("\n");
	
	return 0;
	system("pause");
}



运行结果:

运行结果

参考资料:

时间获取:https://blog.csdn.net/u012229282/article/details/79598287

基姆拉尔森计算公式:https://www.cnblogs.com/fengbohello/p/3264300.html

Q.E.D.