C语言_日期_周计算(二)

日期计算

计算指定日期是周几

void CaculateWeekDay(int y, int m, int d)
{ 
	if (m == 1 || m == 2) { 
		m += 12;
		y--;
	}
	int iWeek = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
	switch (iWeek)
	{ 
	case 0: cout << "星期一" << endl; break;
	case 1: cout << "星期二" << endl; break;
	case 2: cout << "星期三" << endl; break;
	case 3: cout << "星期四" << endl; break;
	case 4: cout << "星期五" << endl; break;
	case 5: cout << "星期六" << endl; break;
	case 6: cout << "星期日" << endl; break;
	}
}

【参考】

  1. C++输入日期判断是星期几

获取一年中周一(日期)的数组

// int array[53][4] = {index, year, month, day}
void GetMondayArray(int y, int(*arr)[4])
{ 
	int m = 1, 
		d = 1, 
		iStart = 1;
	int MonthMax[13]{  31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

	if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)	//如果是闰年
		MonthMax[2] = 29;

	if (m == 1 || m == 2)
	{ 
		m += 12;
		y--;
	}
	int iWeek = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;

	y += 1;
	for (size_t i = 0; i < 53; i++)
		arr[i][0] = i + 1;
	if (iWeek)
	{ 
		arr[0][1] = y - 1;
		arr[0][2] = 12;
		arr[0][3] = 31 - iWeek + 1;
		m = 0;
	}
	else
	{ 
		arr[0][1] = y;
		arr[0][2] = 1;
		arr[0][3] = 1;
		m = 1;
	}

	iStart = arr[0][3];
	for (int i = 1; i < 53; i++)
	{ 
		for (int j = 0; j < 5; j++)
		{ 
			iStart += 7;
			if (iStart > MonthMax[m])
			{ 
				iStart -= MonthMax[m];
				m++;
				m = m > 12 ? 1 : m;
				arr[i][2] = m;
				arr[i][3] = iStart;
				break;
			}
			else
			{ 
				arr[i][1] = y;
				arr[i][2] = m;
				arr[i][3] = iStart;
				i++;
			}
		}
		arr[i][1] = y;
	}
}

int main()
{ 
	int year, month, day;
	/*cout << "请输入年 月 日" << endl; cin >> year; cin >> month; cin >> day; CaculateWeekDay(year, month, day);*/
	int arr[53][4] = {  0 };
	GetMondayArray(2021, arr);
	for (size_t i = 0; i < 53; i++)
	{ 
		printf("%d, %d, %d, %d\n", arr[i][0], arr[i][1], arr[i][2], arr[i][3]);
	}
	system("pause");
	return 0;
}
    原文作者:Been_Stone
    原文地址: https://blog.csdn.net/weixin_42330311/article/details/114439749
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞