获取特定日期所在周的周一至周日的日期范围,并将结果以特定格式的 CString
返回,如20240527_20240602。
注意每次更改完都需要mktime处理
#include <ctime>
#include <iostream>
#include <atlstr.h> // For CString support
// 实现获取指定日期所在周,周一到周日日期范围的函数
CString GetWeekRangeAsString(std::tm& inputDate) {
mktime(&inputDate); // 标准化日期,处理跨月、年情况
// 获取当前日期是星期几(0-周日, 1-周一, ..., 6-周六)
int currentDayOfWeek = inputDate.tm_wday; // 注意tm_wday的值域从0开始,0代表周日
// 计算星期一的日期
std::tm monday = inputDate;
if (currentDayOfWeek != 0) { // 如果不是周日
monday.tm_mday -= (currentDayOfWeek - 1); // 减去距离周日的天数得到周一
mktime(&monday);
}else{
monday.tm_mday-= 6;
mktime(&monday);
}
// 计算星期日的日期
std::tm sunday = monday;
sunday.tm_mday = monday.tm_mday + 6; // 增加到周日的距离
mktime(&sunday);
// 使用stringstream格式化日期为字符串
std::wostringstream wss, wdd;
wss << std::put_time(&monday, L"%Y%m%d");
wdd << std::put_time(&sunday, L"%Y%m%d");
// 将格式化后的字符串转换为CStringW
CString startDateStr(wss.str().c_str());
CString endDateStr(wdd.str().c_str());
// 拼接并返回日期范围字符串
return startDateStr + _T("_") + endDateStr;
}