标准没有定义time_t 是什么类型;它只需要是能够表示时间的真实类型。它可以是整数类型或浮点类型(它不能很复杂——幸运的是)。它不一定是秒数、毫秒数或任何个简单单位。它原则上可以使用位范围以二进制编码的十进制表示月、秒、日、小时、分钟和年按该顺序。最常见的表示是 32 位或 64 位有符号整数,表示自 1970-01-01 00:00:00 UTC 以来的秒数。
如果您想要一种完全可移植的方式来打印time_t 值,您可以检测time_t 的类型:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
int main(void) {
time_t now = time(NULL);
printf("At the sound of the tone, the time will be ... \a");
if ((time_t)1 / 2 != 0) {
// time_t is a floating-point type; convert to long double
printf("%Lf\n", (long double)now);
}
else if ((time_t)-1 > (time_t)0) {
// time_t is an unsigned integer type
printf("%ju\n", (uintmax_t)now);
}
else {
// time_t is a signed integer type
printf("%jd\n", (intmax_t)now);
}
}
这假定 C99 或更高版本的实现。如果您遇到不支持<stdint.h> 和/或%ju 和%jd 格式(您可以通过测试__STDC_VERSION__ 来检测)的C99 之前的实现,您可以转换为@987654329 @ 或 unsigned long 而不是 [u]intmax_t。 (MinGW 可能无法正确处理打印 long double 值,但 MinGW 对 time_t 使用有符号整数类型,所以这不是问题。)
这将打印一个没有意义的原始值,除非您碰巧知道time_t 是如何表示的(它是什么类型和它如何表示当前时间)。在我的系统上,当前时间是 1416589039,这是自 1970-01-01 00:00:00 UTC 以来的秒数(一种非常常见的表示)。
如果您想知道现在是几点,而不是time() 函数返回的原始值,您应该使用<time.h> 中的函数来生成人类可读的表示当前时间。例如:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
int main(void) {
time_t now = time(NULL);
char s[100];
strftime(s, sizeof s, "%F %H:%M:%S %Z", localtime(&now));
printf("The time is now %s\n", s);
}
哪个打印(目前在我的系统上):
The time is now 2014-11-21 08:57:19 PST