如何从time_t中提取小时数?

Dan*_*und 7 c time time-t

我想从表示纪元以来的秒数的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出(小时应为10)

06:15:35
10:15:35

06:15:36
10:15:36

06:15:37
10:15:37
Run Code Online (Sandbox Code Playgroud)

Ada*_*der 12

int h = (t / 3600) % 24;  /* ### Your problem. */
Run Code Online (Sandbox Code Playgroud)


unw*_*ind 5

你的呼叫gmtime()已经完成,结果struct tm有所有字段.请参阅文档.

换句话说,就是

printf("hours is %d\n", tmp->tm_hour);
Run Code Online (Sandbox Code Playgroud)

我认为这是正确的方法,因为它避免了在代码中手动进行大量数字的手动转换.它通过使其成为别人的问题(即,将其抽象化)以最好的方式实现.所以修复你的代码不是通过添加缺失0,而是使用gmtime().

还要考虑时区.

  • @dannas:因为你要划分为:t/360,应该是t/3600(记住60*60) (2认同)