解决mktime在32位的机子上溢出的问题

这篇博客讨论了在32位系统中,由于time_t类型限制导致的时间戳溢出问题,特别是到了2038年时的‘闰年问题’。作者提供了一个解决方案,即通过将mktime函数的返回类型修改为unsigned long long,从而扩展其能够处理的时间范围。此外,还给出了my_mktime函数的实现,用于计算从1970年1月1日至今的秒数,并提供了一个辅助函数time_str_to_second,用于将时间字符串转换为秒数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值