我一直试图简单地将字符串“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 thattm
should be initialized
before the call.
并且memset在同一页面的示例中如上所述使用.