【发布时间】:2012-06-29 20:31:22
【问题描述】:
我想从表示自纪元以来的秒数的 time_t 值中提取小时、分钟和秒作为整数值。
小时值不正确。为什么?
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main()
{
char buf[64];
while (1) {
time_t t = time(NULL);
struct tm *tmp = gmtime(&t);
int h = (t / 360) % 24; /* ### My problem. */
int m = (t / 60) % 60;
int s = t % 60;
printf("%02d:%02d:%02d\n", h, m, s);
/* For reference, extracts the correct values. */
strftime(buf, sizeof(buf), "%H:%M:%S\n", tmp);
puts(buf);
sleep(1);
}
}
输出(小时应该是10)
06:15:35
10:15:35
06:15:36
10:15:36
06:15:37
10:15:37
【问题讨论】:
-
"int h = (t / 3600) % 24; ..." 使 假设
time_t以整数秒为单位。虽然这很常见,但 C 并未定义。可移植代码使用gmtime()/localtime()或difftime()。