【问题标题】:Convert Epoch Time string to Time将纪元时间字符串转换为时间
【发布时间】:2013-01-25 09:42:44
【问题描述】:

我一直在寻找一种将字符串(以纪元时间)转换为日期的方法。

基本上,我需要把这个:1360440555(以字符串形式)写成这个:Feb 9 12:09 2013

我一直在研究 strptime 和 strftime,但似乎都不适合我。有什么建议吗?

编辑:谢谢,伙计们。我用atoi() 将其转换为int,将其转换为time_t,然后在其上运行ctime()。完美运行!

【问题讨论】:

标签: c linux unix time epoch


【解决方案1】:

如果你的值是整数而不是字符串,你可以直接调用ctime。如果只有某种方法可以将字符串转换为整数....

time_t c;
c = strtoul( "1360440555", NULL, 0 );
ctime( &c );

【讨论】:

  • +1 表示讽刺。但它没有任何帮助,如果你问你能不能拼写 strtoul() 会更好。 ctime 需要 time_t 顺便说一句。
  • 不幸的是,没有办法将字符串转换为整数,因为标准库中没有 strtoll() 函数...
  • 注意:在标准 C 中,不能保证 time_t 是自纪元以来的秒数。它在 glibc 但 IDK 关于其他地方。
【解决方案2】:

您可以使用%s (GNU extension),将作为字符串给出的POSIX时间戳转换为分解时间tm

#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include <time.h>

int main() {
    struct tm tm;
    char buf[255];

    memset(&tm, 0, sizeof(struct tm));
    strptime("1360440555", "%s", &tm);
    strftime(buf, sizeof(buf), "%b %d %H:%M %Y", &tm);
    puts(buf); /* -> Feb 09 20:09 2013 */
    return 0;
}

注意:当地时区为UTC(与其他时区结果不同)。

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2015-11-19
    • 2016-07-23
    • 2012-04-03
    • 2018-09-07
    • 2018-02-18
    相关资源
    最近更新 更多