在嘗試編寫比給定時間少返回24小時的代碼時,mktime()
顯示不一致的輸出。我計算它類似於:current_time(GMT) - 86400
應該返回正確的值。我們所需要做的就是根據輸入時間來計算;我們使用mktime()
來更改時間並獲取GMT時間,然後進行常規計算。我在下面列出了我的代碼。mktime顯示不一致的輸出
#include <stdio.h>
#include <time.h>
int main()
{
time_t currentTime, tempTime;
struct tm *localTime;
time(¤tTime);
//localTime = localtime(¤tTime);
localTime = gmtime(¤tTime); //get the time in GMT as we are in PDT
printf("Time %2d:%02d\n", (localTime->tm_hour)%24, localTime->tm_min);
localTime->tm_hour = 19; // Set the time to 19:00 GMT
localTime->tm_min = 0;
localTime->tm_sec = 0;
tempTime = mktime(localTime);
//tempTime = mktime(localTime) - timezone;
printf("Current time is %ld and day before time is %ld\n", currentTime, (currentTime - 86400));
printf("Current timezone is %ld \n", timezone);
printf("New time is %ld and day before time is %ld\n",tempTime, (tempTime - 86400));
}
但是,當我們檢查,便回來後不正確的電話呼叫mktime()
輸出。以下是上述程序的輸出。
$ ./a.out
Time 11:51
Current time is 1341229916 and day before time is 1341143516
New time is 1341284400 and day before time is 1341198000
$ ./print_gmt 1341229916
Mon Jul 2 11:51:56 2012
$ ./print_gmt 1341143516
Sun Jul 1 11:51:56 2012
$ ./print_gmt 1341284400
Tue Jul 3 03:00:00 2012
$ ./print_gmt 1341198000
Mon Jul 2 03:00:00 2012
$ date
Mon Jul 2 04:52:46 PDT 2012
現在,如果我們取消註釋其中減去時區(存在於time.h中)的線,則如預期的輸出。下面是在上面的程序
$ ./a.out
. . .
Current timezone is 28800
. . .
時區的價值那麼,爲什麼是有mktime()
這種不一致的行爲雖然手冊頁不提的時區的這種調整。 在進行此類轉換時是否有某些我們錯過的內容?
在此先感謝。
'timezone'來自哪裏? – alk
'mktime()'假設本地時間不是輸入UTC(又名GMT)。因此,如果不在格林威治,它會增加一個時間轉移。 – alk
@alk,'timezone'是_X/Open System Interfaces Extension_的一部分,在'time.h'中被定義爲'extern long timezone;'。 –