在32位的机子上,time_t是个4字节的值,存储的是1900年到现在的秒数,最大可存放的秒数(时间戳)到2038年多,设置的tm_year不能超过138,多了会溢出,返回异常值。
解决方法:
修改mktime函数的返回值类型
unsigned long -> unsigned long long
unsigned long long my_mktime(const unsigned int year0, const unsigned int mon0,
const unsigned int day, const unsigned int hour,
const unsigned int min, const unsigned int sec)
{
unsigned int mon = mon0, year = year0;
/* 1..12 -> 11,12,1..10 */
if (0 >= (int) (mon -= 2)) {
mon += 12; /* Puts Feb last since it has leap day */
year -= 1;
}
// T = ((X * 24 + hour) * 60 + min) * 60 + sec
// 先算出从1970年1月1日开始的天数X,再进而求出具体的时间值T的
return ((((unsigned long long)
(year/4 - year/100 + year/400 + 367*mon/12 + day) +
year*365 - 719499
)*24 + hour /* now have hours */
)*60 + min /* now have minutes */
)*60 + sec; /* finally seconds */
}
void time_str_to_second(const char *str_time, unsigned long long *out_sec)
{
struct tm tmp_time;
memset(&tmp_time, 0, sizeof(tmp_time));
strptime(str_time, "%Y-%m-%d %H:%M:%S", &tmp_time);
// t = mktime(&tmp_time);
*out_sec = my_mktime(1900+tmp_time.tm_year, tmp_time.tm_mon+1, tmp_time.tm_mday,
tmp_time.tm_hour, tmp_time.tm_min, tmp_time.tm_sec);
}
参考:https://blog.csdn.net/axx1611/article/details/1792827