C标准中的定义
time_t是一种时间类型,一般用来存放自1970年1月1日0点0时0分开始的秒数。
在标准头文件<time.h>中定义的类型别名,具体类型是平台依赖的:
Alias of a fundamental arithmetic type capable of representing times, as those returned by function time. [1]
The range and precision of times representable in clock_t and time_t are implementation-defined.
一般定义为有符号的整型或有符号的长整型。有符号,是因为有些时间库函数返回的time_t值,可能为负数。
各系统的实现
OS | Real Type | Implementation |
SUSE Linux | long int |
|
AIX | 64位编译模式:long 32位编译模式:long Linux兼容模式:long |
|
HP-UX | 内核模式:int std命名空间:long |
|
鸡肋
time_t被认为是内存中的类型,当需要保存到文件、内存数据库或网络传输时,平台依赖的类型成为了问题,无法确定它的长度。
如果要在C代码中输出它的值,我们大概会这样写:
time_t rawtime = time(NULL);
printf("%ld", (long)rawtime);
可以摒弃time_t,定义自己的时间类型:
typedef long long time_t1;
而C库时间函数的时间类型均是time_t,如果使用自定义的类型,编译时有可能报警告。
2038年问题
32位的程序,如果time_t定义为32位的整型,则存在2038年问题。
有符号整型的最大值是:2147483647,它所表示的最大时间(1970年1月1日0时0分0秒,加上2147483647秒)是2038年1月19日3时14分7秒,以下是一个测试程序:
#include <time.h>
#include <stdio.h>
#include <limits.h> /* INT_MAX */
int main()
{
time_t rawtime = INT_MAX;
struct tm* ptm = gmtime(&rawtime);
char timestr[50] = {0};
/* format: YYYY/MM/DD HH24:MI:SS */
strftime(timestr, sizeof(timestr), "%Y/%m/%d %H:%M:%S", ptm);
printf("INT_MAX(%d) represent time: %s.\n", INT_MAX, timestr);
return 0;
}
程序输出为:
INT_MAX(2147483647) represent time: 2038/01/19 03:14:07.
有一种解决方案是,则time_t定义为无符号的整型,它可以表示的最大时间是://TO BE CONTINUE...