【问题标题】:Converting a UNIX Timestamp to seconds/minutes/hours/months/years using C使用 C 将 UNIX 时间戳转换为秒/分钟/小时/月/年
【发布时间】:2014-04-30 15:12:00
【问题描述】:

使用 C,我想将一个 UNIX 时间戳数字转换为几个常用的日期数据。

如何在使用 C 时将 UNIX 时间戳(如 12997424)转换为表示秒、分钟、小时和天的不同数字?

【问题讨论】:

    标签: c date unix timestamp


    【解决方案1】:

    使用标准库中的gmtimelocaltime。原型在 time.h 中定义。

    添加和编辑:

    例如,以下代码打印当前时间戳、小时和分钟:

    #include <stdio.h>
    #include <time.h>
    
    void main() {
        time_t      t;
        struct tm   ttm;
    
        t = time(NULL);
        printf("Current timestamp: %d\n", t);
        ttm = * localtime(&t);
        printf("Current time: %02d:%02d\n", ttm.tm_hour, ttm.tm_min);
    }
    

    【讨论】:

    • +1 Marian 以获得正确答案,但可能值得用一个例子来充实,所以 OP 可以看到如何使用调用以及生成的 struct tm
    • 感谢您的帮助!我对编程(用C语言)不是很有经验。我试图了解如何将 UNIX 时间戳(表示从 1970 年 1 月 1 日到我正在使用的代码中设置的日期的秒数)转换为多个日期数据,但不幸的是我根本没有得到它。我在哪里可以传入 UNIX 时间戳数据(以秒为单位)以便进行转换?
    • @Klyner time_t 类型的变量 t 是 Unix 时间戳。您可以将time_t 类型理解为int
    • 谢谢!这解释了很多!
    【解决方案2】:

    这是一个如何使用 localtime 将 time_t 转换为 tm 作为本地时间的示例(信用转到 www.cplusplusreference.com):

    #include <stdio.h>
    #include <time.h>
    
    int main() {
      time_t rawtime;
      struct tm * timeinfo;
    
      time (&rawtime);
      timeinfo = localtime (&rawtime);
      printf ("Current local time and date: %s", asctime(timeinfo));
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 2011-04-14
      • 2017-11-22
      相关资源
      最近更新 更多