加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将字符串时间转换为unix时间,反之亦然

发布时间:2020-12-16 03:43:14 所属栏目:百科 来源:网络整理
导读:我一直试图简单地将字符串“1998-04-11”转换为UNIX时间戳,根据在线转换器应该是892245600. 但我一直得到不同的结果. 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)
我一直试图简单地将字符串“1998-04-11”转换为UNIX时间戳,根据在线转换器应该是892245600.

但我一直得到不同的结果.

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

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

解决方法

在调用strptime之前将tm结构归零
memset(&tm,sizeof(struct tm));

来自http://man7.org/linux/man-pages/man3/strptime.3.html的笔记部分

In principle,this function does not initialize tm but stores only
the values specified. This means that tm should be initialized
before the call.

并且memset在同一页面的示例中如上所述使用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读