mktime()函数的奇怪现象

jackydi 2019-05-17 01:58:47
今天把程序从centos6.5移植到centos7.5下,发现一个奇怪的问题,经排查,发现和mktime()函数有关,测试代码如下:


#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>
#include <stdint.h>

#define STR_TO_INT(x) strtoul(x, 0, 10)

int check_time(char **str1, uint64_t *ret)
{
int len, i;
char *p, p1[5];
time_t tmt;
struct tm t;
char *str = *str1;
char tmp[15];

if (str == NULL)
{
*ret = 0;
return 0;
}

len = strlen(str);
if (len > 14) /* YYYYMMDDhhmmss */
{
str[14] = 0;
len = strlen(str);
}

for (i=0; i<len; i++)
{
if ((str[i] < '0') || (str[i] > '9'))
return -1;
}

strncpy(tmp, str, 14);
for (i=len; i<14; i++)
{
tmp[i]='0';
}
tmp[14] = '\0';

p = tmp;
memcpy(p1, p, 4);
p1[4]=0;
p += 4;
t.tm_year = STR_TO_INT(p1);
if (t.tm_year<=1900)
t.tm_year = 1900;
t.tm_year -= 1900;

memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_mon = STR_TO_INT(p1);
if (t.tm_mon == 0)
t.tm_mon = 1;
else if (t.tm_mon > 12)
return -1;
t.tm_mon -= 1;

memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_mday = STR_TO_INT(p1);
if (t.tm_mday == 0)
t.tm_mday = 1;
else if (t.tm_mday > 31)
return -1;

memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_hour = STR_TO_INT(p1);
if (t.tm_hour>23)
return -1;

memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_min = STR_TO_INT(p1);
if (t.tm_min>59)
return -1;

memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_sec = STR_TO_INT(p1);
if (t.tm_sec>59)
return -1;

t.tm_isdst = 0;

printf("%d\n",t.tm_isdst);

printf("%d-%d-%d %d:%d:%d\n",t.tm_year, t.tm_mon, t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);

tmt = mktime(&t);
printf("%llu\n", tmt);

localtime_r(&tmt, &t);

printf("%d-%d-%d %d:%d:%d\n",t.tm_year, t.tm_mon, t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);
*ret = tmt*1000;
return 0;
}

int main(int argc, char ** argv)
{
uint64_t t;

check_time(&argv[1], &t);
printf("t=%llu\n", t);
return 0;
}


这段代码在centos6.5上没有问题,在centos7.5上打印输出就不一样,不知道怎么回事?

在centos 6.5上测试如下:

[root@sslever test]# gcc -o t tt.c
[root@sslever test]# ./t 201904191025
0
119-3-19 10:25:0
1555640700
119-3-19 10:25:0
t=1555640700000

[root@sslever test]#


在centos 7.5 下测试如下:

[root@centos7-1804 test]# ./t 201904191025
0
119-3-19 10:25:0
1555687500
119-3-19 11:25:0
t=1555687500000

[root@centos7-1804 test]#

同样的输入参数,在centos 6.5上转换时间就是正常的,也能正确转换回来,在centos 7.5上就不对,使用mktime()函数之后转换就是错的,不知道怎么回事?
...全文
139 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jackydi 2019-05-17
  • 打赏
  • 举报
回复
引用 2 楼 636f6c696e 的回复:
估计是两个版本实现不一致吧,可以看看RN有没有提到


RN是什么东东?
636f6c696e 2019-05-17
  • 打赏
  • 举报
回复
估计是两个版本实现不一致吧,可以看看RN有没有提到
jackydi 2019-05-17
  • 打赏
  • 举报
回复
刚刚发现这个转换居然还受到系统时间格式的影响,我centos 6.5设置的是24小时显示格式,centos 7.5设置的是12小时显示格式,结果在centos 7.5上转换后总是要比原来多13个小时的时间,重新设置为24小时显示格式后,再使用上面的测试函数测试就显示正确了,不知道怎么回事?哪位大牛能解释一下?

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧