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

lyr7nygr  于 2023-01-29  发布在  Unix
关注(0)|答案(2)|浏览(139)

我们如何将C语言中的Unix时间戳转换为日:月:日:年?例如,如果我的Unix时间戳是1230728833(int),我们如何将这个值转换为-〉Thu Aug 21 2008?
谢谢你,

8i9zcol2

8i9zcol21#

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

r1zk6ea12#

这段代码帮助您将时间戳从系统时间转换为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;
}

相关问题