time_t

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值,可能为负数。

各系统的实现

OSReal TypeImplementation
SUSE Linuxlong int
/* /usr/includebits/typesizes.h */
#define __TIME_T_TYPE           __SLONGWORD_TYPE


/* /usr/include/bits/types.h */
#define __SLONGWORD_TYPE        long int
#if __WORDSIZE == 32
/* We want __extension__ before typedef's that use nonstandard base types
   such as `long long' in C89 mode.  */
# define __STD_TYPE             __extension__ typedef
#elif __WORDSIZE == 64
/* No need to mark the typedef with __extension__.   */
# define __STD_TYPE             typedef
#else
# error
#endif

__STD_TYPE __TIME_T_TYPE __time_t;      /* Seconds since the Epoch.  */

/* /usr/include/time.h */
typedef __time_t time_t;
AIX

64位编译模式:long

32位编译模式:long

Linux兼容模式:long

/* /usr/include/time.h */
#ifndef _TIME_T
#define _TIME_T
#ifdef  _LINUX_SOURCE_COMPAT
typedef long int        time_t;
#else   /* !_LINUX_SOURCE_COMPAT */
#ifdef __64BIT__
typedef long            time_t;
#else
typedef int             time_t;
#endif
#endif  /* !_LINUX_SOURCE_COMPAT */
#endif
HP-UX

内核模式:int

std命名空间:long

/* /usr/include/sys/_time_t.h */
#  ifndef _TIME_T
#    define _TIME_T
#    ifdef _KERNEL
typedef int32_t time_t;
#    else /* !_KERNEL */
_NAMESPACE_STD_START
typedef long time_t;
_NAMESPACE_STD_END
#    endif /* !_KERNEL */
#  endif /* _TIME_T */


鸡肋

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...

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值