c - time_t 环绕日期

标签 c date

我试图找出时间将溢出 time_t 值的日期

#include <stdio.h>
#include <time.h>
#include <limits.h>

main(){
      time_t now,end;
      now=time(NULL);
      end=LONG_MAX;
      printf("Current date : %s\n",ctime(&now));
      printf("Date of death : %s\n",ctime(&end));
}

我发现在我的系统上 time_t 和 LONG_MAX 一样是 8 个字节。当我运行它时,我得到:

当前日期:2015 年 2 月 1 日星期日 17:29:09 和,死亡结束日期:(null) 但是当我设置 end=INT_MAX; 我得到 Date of Death : Tue Jan 05:14:07 2038 那么为什么我得到 (null) with LONG_MAX?而不是正常的约会

最佳答案

64 位长将在 292,277,026,596 年左右的某个地方进行环绕,这是从现在算起的宇宙当前年龄的 20 倍左右。由于地球自转不太可能一直持续到那个时候,人们也不会真正关心,所以那个时候很容易返回 (null)


开个玩笑,真正的原因很可能是 ctime 算法可能使用 localtimetime_t 转换为故障时间,而那使用 int 作为年份值。


以下 python 脚本可用于查找 time_t 的最大值,ctime 不会抛出异常(它是 libc ctime,C 中的实现留给读者作为练习):

import time

t = 0
for i in range(56, -1, -1):
    try:
        newt = t + (2 << i)
        time.ctime(newt)
        t = newt
    except ValueError:
        pass

print("Maximum value", bin(t))
print("Date at maximum", time.ctime(t))

我电脑上的代码输出,glibc 2.19:

Maximum value 0b11110000110000101001110110000110100010111110000101011010
Date at maximum Tue Dec 31 23:59:52 2147483647

2147483647 是 2 ^ 31 - 1。

关于c - time_t 环绕日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264458/

相关文章:

c - 从 yylex 返回 "non-ints"

C字符串使用指针

javascript - 如何从 Javascript 或 Typescript 的常规日期列表中过滤本周的日期?

python - 比较 python 中的 unicode 和 datetime.datetime

ORACLE 不保存日期时间。为什么?

c - 如何在c中正确格式化整数?

c++ - 将值作为函数参数传递还是计算两次?

c - MATLAB 上的 GMT 减法

postgresql - Postgresql 中的日期绑定(bind)运行平均值 - 如何划分为四个星期

java - Java/Android 中的月份循环