2014-12-21 165 views
0

我有2个时间字符串,并希望找到它们之间的区别。我的代码有效。但是当我尝试相同的值时它显示不同的输出。这里是我的代码:找到时间之间的差异c

#include <time.h> 
    #include <stdio.h> 
    time_t convtotime(char *time_detail,char *format){ 
     struct tm tm; 
     strptime(time_detail,format,&tm); 
     time_t t = mktime(&tm); 
     return t; 

    } 
    int main(int argc, char const *argv[]) 
    { 
     char buff[25]; 
     time_t newtime = convtotime("12/Dec/2014:10:44:19","%d/%b/%Y:%H:%M:%S"); 
     time_t oldtime = convtotime("12/Dec/2014:10:44:35","%d/%b/%Y:%H:%M:%S"); 
     printf("%lf",difftime(oldtime,newtime)); 
    } 

,并将其输出:

3616.000000 

16.000000 
+0

你的意思是说,当再次运行这个精确的程序时你会得到不同的结果吗? – usr2564301

+0

Yessssssssssss。 – Odko

回答

2

manual for strptime说:

原则上,此功能不会初始化TM但只存储 的价值es指定。 这意味着应在 呼叫之前初始化tm。

所以尝试:

struct tm tm = {0}; 
strptime(time_detail, format, &tm); 

the standard的措辞也很有趣:

它是使用相同的 TM结构将更新当前未指定的多个调用是否strptime()该结构的内容或 将覆盖该结构的所有内容。

+0

所以观察到的One Hour偏移是由于包含一些随机值的'tm'的夏令时成员。接得好! – usr2564301