【问题标题】:How to extract hours from time_t?如何从 time_t 中提取小时数?
【发布时间】: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()

标签: c time time-t


【解决方案1】:
int h = (t / 3600) % 24;  /* ### Your problem. */

【讨论】:

  • 哎呀,为什么我没有看到那个明显的?
  • 我认为每个人有时都会看到一个错误并没有看到它。它经常对我来说;)
【解决方案2】:

您对gmtime() 的调用已经完成,生成的struct tm 包含所有字段。见the documentation

换句话说,就是

printf("hours is %d\n", tmp->tm_hour);

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

还要考虑时区。

【讨论】:

  • 谢谢,但问题是:为什么计算不正确。 (我同意使用 struct tm 是一种更好的方法)。
  • @dannas:因为你划分为:t/360 应该是 t/3600(记住 60 * 60)
  • 嗯,问题实际上是:“如何从 time_t 中提取小时数”(在问题规范中我添加了另一个问题)。接受答案,因为它提供了一个很好的理由说明为什么我应该避免自己进行转换。
猜你喜欢
  • 2020-07-31
  • 1970-01-01
  • 2011-06-22
  • 2020-07-07
  • 2022-01-06
  • 2019-06-10
  • 1970-01-01
  • 2019-05-27
  • 2021-01-06
相关资源
最近更新 更多