經過日期時間點,獲取該日期所屬周時間段,好比20190117 返回20190114-20190120spa
string GetWeekPeriodByDate(string sDate) { string sPeriod = ""; int nLength = sDate.length(); if (8 != nLength) return sPeriod; int y = atoi(sDate.substr(0, 4).c_str()); int m = atoi(sDate.substr(4, 2).c_str()); int d = atoi(sDate.substr(6, 2).c_str()); //檢測時間有效性 if (y < 1900) return sPeriod; if (m < 1 || m > 12) return sPeriod; if (d < 1 || d > 31) return sPeriod; //日期 轉 時間戳 struct tm t; t.tm_year = y - 1900;//年份,其值等於實際年份減去1900 t.tm_mon = m - 1; //月份(從一月開始,0表明一月) - 取值區間爲[0,11] t.tm_mday = d; //一個月中的日期 - 取值區間爲[1,31] t.tm_hour = 0; //時 - 取值區間爲[0,23] t.tm_min = 0; //分 - 取值區間爲[0,59] t.tm_sec = 0; //秒 – 取值區間爲[0,59] t.tm_isdst = 0; //夏令時標識符,實行夏令時的時候,tm_isdst爲正。不實行夏令時的進候,tm_isdst爲0 time_t t_of_day; t_of_day = mktime(&t); //獲取日期爲星期幾 if (m == 1 || m == 2) //把一月和二月換算成上一年的十三月和是四月 { m += 12; y--; } int nDayth = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7; //獲取日期對應同屬周 星期一和星期日 time_t t_of_monday = t_of_day - nDayth * 24 * 3600; time_t t_of_sunday = t_of_day + (6 - nDayth) * 24 * 3600; char s[100]; struct tm *p = localtime(&t_of_monday); strftime(s, sizeof(s), "%Y%m%d", p); string sMonday(s); p = localtime(&t_of_sunday); strftime(s, sizeof(s), "%Y%m%d", p); string sSunday(s); sPeriod = sMonday + "-" + sSunday; return sPeriod; }