前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用strptime函数时遇到的一个坑

使用strptime函数时遇到的一个坑

原创
作者头像
jackieluo
修改2018-07-17 20:42:33
2.1K0
修改2018-07-17 20:42:33
举报
文章被收录于专栏:Jackie技术随笔Jackie技术随笔

做新专辑排序的需求时,需要对专辑的时间进行排序,由于目前该字段是字符串类型的日期,在排序函数中要转成标准的UNIX时间戳来进行对比,大概代码如下:

代码语言:txt
复制
struct tm tm1;
strptime(string("2018-01-18").c_str(), "%Y-%m-%d", &tm1);
time_t t1 = mktime(&tm1);
std::cout << t1 << endl;

struct tm tm2;
strptime(string("2011-11-11").c_str(), "%Y-%m-%d", &tm2);
time_t t2 = mktime(&tm2);
std::cout << t2 << endl;

std::cout << "result:" << ((t1 > t2) ? "true" : "false") << endl;

一个很简单的字符串转时间戳进行比较的逻辑,但是运行后发现,mktime()返回的时间戳很随机,明显有异常。

代码语言:txt
复制
3175021632//错误的时间戳
1320966000
result:true
...
2765263112//错误的时间戳
1320966000
result:true

查看mktime()的API:

Notes If the std::tm object was obtained from std::get_time or the POSIX strptime, the value of tm_isdst is indeterminate, and needs to be set explicitly before calling mktime.

这里有提到说如果是从strptime()取到的值,tm_isdst的值是不确定的,必须手动指定。因此想到,是否对于未做初始化的struct tmstrptime()函数并不会去给每个值赋值。查看strptime

It is unspecified whether multiple calls to strptime() using the same tm structure will update the current contents of the structure or overwrite all contents of the structure. Conforming applications should make a single call to strptime() with a format and all data needed to completely specify the date and time being converted.

因此,解决方法就是在使用strptime()之前,对结构体进行零初始化(zero-initialize)

代码语言:txt
复制
struct tm tm1 = {0};
...
struct tm tm2 = {0};

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档