【发布时间】:2012-07-02 20:27:40
【问题描述】:
在尝试编写返回比给定时间少 24 小时的代码时,mktime()显示不一致的输出。我计算它类似于这样:current_time(GMT) - 86400 应该返回正确的值。我们需要做的就是根据输入的时间进行计算;我们使用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来自哪里? -
mktime()假定输入是本地时间而不是 UTC(又名 GMT)。因此,如果不在格林威治,它会增加一个时移。 -
@alk,
timezone是 X/Open System Interfaces Extension 的一部分,在time.h中定义为extern long timezone;。 -
@HristoIliev 哎呀,是的.. - 谢谢你指点我这个。