【问题标题】:C string representation of time_t [duplicate]time_t的C字符串表示[重复]
【发布时间】:2017-07-19 02:45:45
【问题描述】:

我需要将 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

【问题讨论】:

  • printf("Current date and time are: %d\n", (int)Time_Epoch);

标签: c string timestamp type-conversion


【解决方案1】:

如果目标是将time_t 的值存储在一个字符数组中,您可以使用sprintf 作为:

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

【讨论】:

    猜你喜欢
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2021-12-26
    • 2016-09-15
    • 2016-12-11
    • 2010-09-24
    • 1970-01-01
    相关资源
    最近更新 更多