在 C 中打印时间(0)的格式说明符 [英] Format specifier to print time(0) in C
问题描述
我们可以声明一个变量来保存来自系统的当前时间:
We can declare a variable to hold the current time from the system using:
time_t now = time(0);
time(0)
也可用于生成随机值:
time(0)
can also be use in generating random values:
#define SEED time(0);
srand((unsigned int )SEED);
我的问题是:time(0)
究竟是什么.默认情况下,long
类型是毫秒吗?如果要打印time(0)
的值,可以用"%d"
打印出来吗?(Sicne printf()
要求我们传入它需要的类型,但我怎么知道 time(0)
的类型是什么?).
My question is: What exactly is time(0)
. By default is it in milliseconds with type long
? If I want to print out the value of time(0)
, can I use "%d"
to print it out? (Sicne printf()
requires us to pass in the type it requires, but how can I know what is the type of time(0)
?).
如果是 time_t
类型,我应该在 printf 中使用什么格式说明符?
If it is of type time_t
, what format specifier should I use in printf?
推荐答案
time_t
由 C 标准,C11,7.27.1/3 定义为:
time_t
is defined by C standard, C11, 7.27.1/3 as:
[...] 是能够表示时间的实数类型;
[...] which are real types capable of representing times;
这意味着它可以是 int、long、unsigned long、double 或任何其他实数类型.基本上这是一个实现的选择.同样,它也没有定义 time_t
返回什么单位,C11, 7.27.2.4/3:
That means it could be int, long, unsigned long, double or any other real type. Basically it's an implementation's choice. Similarly, it doesn't define what units time_t
returns either, C11, 7.27.2.4/3:
时间函数返回实现的最佳近似值到当前日历时间.返回值 (time_t)(-1)如果日历时间不可用.如果计时器不为空指针,返回值也赋值给它指向的对象.
The time function returns the implementation’s best approximation to the current calendar time. The value (time_t)(-1) is returned if the calendar time is not available. If timer is not a null pointer, the return value is also assigned to the object it points to.
您必须阅读您的实现内容.我在 Linux 上的 glibc 实现说,time_t 返回的单位是秒.所以你可以将它转换为 uintmax_t
并打印:
You'll have to read what your implementation says. The glibc implementation I have on my Linux says, the unit returned by time_t is in seconds. So you could convert it to uintmax_t
and print:
time_t tvalue = time(0);
printf("%ju", (uintmax_t)tvalue);
或者你可以使用 difftime() 返回一个double
作为两个 time_t
值之间的差异,这样您就不必担心 time_t
的底层类型.
Or you could use difftime() which returns a double
as difference between two time_t
values so that you don't have to worry about the underlying type of time_t
.
这篇关于在 C 中打印时间(0)的格式说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!