【问题标题】:Convert string time to unix time and vice versa将字符串时间转换为 unix 时间,反之亦然
【发布时间】:2016-03-03 06:16:26
【问题描述】:

我一直在尝试将字符串“1998-04-11”简单地转换为根据在线转换器应该是 892245600 的 UNIX 时间戳。

但我不断得到不同的结果。

    struct tm tm;
    time_t ts;

    strptime("1998-04-11", "%Y-%m-%d", &tm);
    tm.tm_mon = tm.tm_mon -1;
    ts = mktime(&tm);

    printf("%d \n", (int)ts); //unix time-stamp
    printf("%s \n", ctime(&ts)); //human readable date 

结果:

893502901
Sat Apr 25 13:15:01 1998

谁能告诉我我做错了什么?

【问题讨论】:

  • 在在线转换器和您的本地机器中使用相同的时区?
  • 如何检查?另外,我如何得到与我输入的完全不同的日期?这和当地时间有关吗?

标签: c++ unix-timestamp


【解决方案1】:

在调用strptime之前将tm结构归零

memset(&tm, 0, sizeof(struct tm));

来自注释部分:http://man7.org/linux/man-pages/man3/strptime.3.html

这个函数原则上不初始化tm,只存储 指定的值。这意味着应该初始化tm 通话前。

并且memset在同一页面的示例中与上面一样使用。

【讨论】:

  • 这行得通。而且我不必再使用tm.tm_mon = tm.tm_mon -1;。非常感谢。
【解决方案2】:

这是内存未初始化的问题。

(gdb) p tm
$1 = {tm_sec = 1, tm_min = 0, tm_hour = 4196061, tm_mday = 0, tm_mon = -5984, tm_year = 32767, 
tm_wday = 0, tm_yday = 0, tm_isdst = 4195984, tm_gmtoff = 4195616, 
tm_zone = 0x7fffffffe980 "\001"}

正如您在调试器中看到的,struct tm 分配了随机内存。使 time_zone 偏移成为垃圾。

strptime 运行后:

(gdb) p tm
$3 = {tm_sec = 1, tm_min = 0, tm_hour = 4196061, tm_mday = 11, tm_mon = 3, tm_year = 98, 
tm_wday = 6, tm_yday = 100, tm_isdst = 4195984, tm_gmtoff = 4195616, 
tm_zone = 0x7fffffffe980 "\001"}

另外:

tm.tm_mon = tm.tm_mon -1;

没有必要。更正代码:

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

int main(int argc, char **argv) {

struct tm tm;
time_t ts = 0;
memset(&tm, 0, sizeof(tm));

    strptime("1998-04-11", "%Y-%m-%d", &tm);
    ts = mktime(&tm);

    printf("%d \n", (int)ts); //unix time-stamp
    printf("%s \n", ctime(&ts)); //human readable date
}

输出:

892252800
Sat Apr 11 00:00:00 1998

【讨论】:

  • 谢谢,这是一个很好的解释,可以更好地理解这个过程。
猜你喜欢
  • 2019-03-20
  • 2021-08-31
  • 2013-01-30
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
相关资源
最近更新 更多