纪元时间转换成date/time格式

Epoch time into date/time format

我有一个包含纪元时间的字符,我正在尝试将其转换为 date/time 格式 YYYY/mm/dd/HH:MM:SS,

我一直在使用 strftime,但似乎无法正确使用,

谁能帮帮我?

            time_t eventFinish = endTime;
            struct tm *tm2 = localtime(&eventFinish);
            //syslog( LOG_INFO, "eventFinish:: %s", eventFinish);
            char buf2[64];
            strftime( buf2, sizeof( buf2 ), "%Y%m%d%H%M%S", &tm2 );
            syslog( LOG_INFO, "Your time: %s", buf2 );

eventFinish 输出我期望的纪元时间,buf2 输出随机数。

您必须先将您的 unix 时间戳转换为 struct tm

time_t ts = 1562230784; // current time as example
struct tm *tm = localtime(&ts);

然后将其与 strftime() 一起使用:

char buf[64];
strftime(buf, sizeof(buf), "%Y/%m/%d/%H:%M:%S", tm);
printf("Your time: %s\n", buf);

相关结构在time.h中定义。 这应该可以做你想做的事。

请注意,这将 return 系统中配置的本地时区时间。要获取 UTC,您可以使用 gmtime() 而不是 localtime()