time_t的C字符串表示

时间:2017-02-28 08:20:57

标签: c string timestamp type-conversion

我需要将time_t存储为char数组中的字符串。 关于将time_t转换为字符串还有一些其他问题,但它们对我没有帮助。我想将time_t的值存储在一个字符串中,而不是将其转换为人类可读的格式。请在回答之前先查看this question

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

int main()
{
    struct tm epoch_date;
    time_t Time_Epoch;
    strptime("2017 Jan 1 23:59:59", "%Y %b %d %T", &epoch_date);

    Time_Epoch = timegm(&epoch_date); // Time_Epoch: 1488268396
    return 0;
}

这段代码将时间戳返回为Time_Epoch。

我应该如何将该时间戳转换为字符串以提供所需的输出,如下所示:

所需的输出:Current date and time are: 1488268396

1 个答案:

答案 0 :(得分:1)

如果目标是将time_t的值存储在char数组中,则可以使用sprintf作为:

char strTime[50];
sprintf(strTime,"%d",Time_Epoch);