【问题标题】:Convert UTC to days, hours minutes etc in C在 C 中将 UTC 转换为天、小时、分钟等
【发布时间】:2010-10-14 01:48:38
【问题描述】:

我有一个 long ,它有 UTC 格式的时间作为某些数据的时间戳,现在我想将其转换为这种格式: 第 1-12 个月 第 1-31 天 24 小时制 0-23 分钟 0-59 秒 0-59 亚秒纳秒 0-999,999,999

现在纳秒显然可以设置为 0,因为它不需要那么精确。

最好的方法是什么?我看过很多示例,但它们令人困惑,似乎不适用于转换任意日期,它们仅适用于转换当时的确切时间。

【问题讨论】:

  • 任何严格的 UTC 函数都将返回 [0, 60] 秒(60 是闰秒),但是,许多实现忽略了这一点。请注意您选择的任何实现方式。

标签: c datetime date time


【解决方案1】:

给你。注意注释行

#include <stdio.h>
#include <time.h>

int main(void) {
  char buf[512];
  long stamp = 1287055578;
  struct tm x;
  time_t cstamp = stamp;       /* 1 */
  x = *gmtime(&cstamp);        /* 2 */

  sprintf(buf, "month %d Day %d 24 Hour format %d minute %d second %d "
               "subsecond nanoseconds 0",
               x.tm_mon + 1, x.tm_mday, x.tm_hour, x.tm_min, x.tm_sec);

  printf("%s\n", buf); /* long converted to string */
  return 0;
}

1) gmtime 采用 time_t* 类型的值,因此我将 long 隐式转换为 time_t 并在下一步中传递该地址

2) gmtime 返回一个指向 struct tm 对象的指针。取消引用该指针并将对象复制到我的本地 x 变量

您可能希望使用localtime 来代替gm_time,并让库函数处理时区和夏令时问题。

【讨论】:

    【解决方案2】:

    您可能想查看ctime 标头。 asctimestrftimectime 等将时间转换为字符串。

    【讨论】:

      【解决方案3】:

      感谢大家的回答,我最终是这样做的

      long UTCInSeconds = ...
      
      struct tm * local;
      local = localtime(UTCInSeconds);
      
      Month = local->tm_mon + 1;
      Day = local->tm_mday;
      Year = local->tm_year + 1900;
      Hour = local->tm_hour;
      Minute = local->tm_min;
      Second = local->tm_sec;
      

      【讨论】:

        猜你喜欢
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        • 2014-12-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 2010-10-08
        相关资源
        最近更新 更多