2014-12-21 166 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