C语言 如何在C中将Unix时间戳转换为日:月:日:年格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18582119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:20:48  来源:igfitidea点击:

How to convert Unix TimeStamp into day:month:date:year format in C?

cunix-timestamp

提问by user2430771

How do we convert a Unix time stamp in C to day:month:date:year? For eg. if my unix time stamp is 1230728833(int), how we convert this value into this-> Thu Aug 21 2008?

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

Thanks,

谢谢,

回答by sjnarv

Per @H2CO3's proper suggestion to use strftime(3), here's an example program.

根据@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;
}

回答by Varun P

This code helps you to convert timestamp from system time into UTC and TAI human readable format.

此代码可帮助您将时间戳从系统时间转换为 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);
        year_pr = ts.tm_year;
        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;
}