【问题标题】:How to convert Unix TimeStamp into day:month:date:year format in C?如何在 C 中将 Unix TimeStamp 转换为日:月:日:年格式?
【发布时间】:2013-09-06 02:06:55
【问题描述】:

我们如何将 C 中的 Unix 时间戳转换为日:月:日:年?例如。如果我的 unix 时间戳是 1230728833(int),我们如何将此值转换为 this-> Thu Aug 21 2008?

谢谢,

【问题讨论】:

  • 顺便说一句,与您的 Unix 时间戳对应的日期是 2008 年 12 月 31 日...
  • 非常感谢.. 真的很有帮助。

标签: c unix-timestamp


【解决方案1】:

根据@H2CO3 的正确建议使用strftime(3),这是一个示例程序。

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

static const time_t default_time = 1230728833;
static const char default_format[] = "%a %b %d %Y";

int
main(int argc, char *argv[])
{
        time_t t = default_time;
        const char *format = default_format;

        struct tm lt;
        char res[32];

        if (argc >= 2) {
                t = (time_t) atoi(argv[1]);
        }

        if (argc >= 3) {
                format = argv[2];
        }

        (void) localtime_r(&t, &lt);

        if (strftime(res, sizeof(res), format, &lt) == 0) {
                (void) fprintf(stderr,  "strftime(3): cannot format supplied "
                                        "date/time into buffer of size %u "
                                        "using: '%s'\n",
                                        sizeof(res), format);
                return 1;
        }

        (void) printf("%u -> '%s'\n", (unsigned) t, res);

        return 0;
}

【讨论】:

    【解决方案2】:

    此代码可帮助您将时间戳从系统时间转换为 UTC 和 TAI 人类可读格式。

    #include <stdio.h>
    #include <time.h>
    #include <unistd.h>
    
    int main(void)
    {
        time_t     now, now1, now2;
        struct tm  ts;
        char       buf[80];
    
     
            // Get current time
            time(&now);
            ts = *localtime(&now);
            strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S", &ts);
            printf("Local Time %s\n", buf);
    
            //UTC time
            now2 = now - 19800;  //from local time to UTC time
            ts = *localtime(&now2);
            strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S", &ts);
            printf("UTC time %s\n", buf);
    
            //TAI time valid upto next Leap second added
            now1 = now + 37;    //from local time to TAI time
            ts = *localtime(&now1);
            strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S", &ts);
            printf("TAI time %s\n", buf);
            return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      相关资源
      最近更新 更多