c - 在 C 中打印时间 (0) 的格式说明符

标签 c time types

我们可以声明一个变量来保存系统的当前时间:

time_t now = time(0);

time(0) 也可用于生成随机值:

#define SEED time(0);
srand((unsigned int )SEED);

我的问题是:time(0) 究竟是什么。默认情况下,它以毫秒为单位,类型为 long?如果我想打印出time(0)的值,可以用"%d"打印出来吗? (Sicne printf() 要求我们传入它需要的类型,但是我怎么知道 time(0) 的类型是什么?)。

如果是 time_t 类型,我应该在 printf 中使用什么格式说明符?

最佳答案

time_t 由 C 标准,C11,7.27.1/3 定义为:

[...] which are real types capable of representing times;

这意味着它可以是 int、long、unsigned long、double 或任何其他实数类型。基本上这是一个实现的选择。同样,它也没有定义 time_t 返回的单位,C11,7.27.2.4/3:

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 并打印:

time_t tvalue = time(0);
printf("%ju", (uintmax_t)tvalue);

或者您可以使用 difftime()它返回一个 double 作为两个 time_t 值之间的差异,因此您不必担心 time_t 的基础类型。

关于c - 在 C 中打印时间 (0) 的格式说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27057677/

相关文章:

MySQL从毫秒字段中选择格式化日期

c# - 如何获取进程 “type”(应用程序,后台进程或Windows进程)

c - rdtsc,循环太多

c - 调试文件格式困惑: ELF/BIN

c++ - Unix 函数 gmtime_r 的 Windows 等价物是什么?

javascript - 如何在java脚本中检查时间是否小于或等于特定小时

function - 具有不同参数子类型的 Julia 函数

mysql - 由于数据类型, '' 中的未知列 'field list'

c - 在 C 中传递子字符串

c - sprintf 前置额外的字符