I have the following code:
我有以下代码:
struct tm time;
strptime("27052010", "%d%m%Y", &time);
cout << "sec: " << time.tm_sec << "\n";
cout << "min: " << time.tm_min << "\n";
cout << "hour: " << time.tm_hour << "\n";
cout << "day: " << time.tm_mday << "\n";
cout << "month: " << (time.tm_mon + 1) << "\n";
cout << "year: " << time.tm_year << "\n";
time_t t = mktime(&time);
cout << "sec: " << time.tm_sec << "\n";
cout << "min: " << time.tm_min << "\n";
cout << "hour: " << time.tm_hour << "\n";
cout << "day: " << time.tm_mday << "\n";
cout << "month: " << (time.tm_mon + 1) << "\n";
cout << "year: " << time.tm_year << "\n";
cout << "time: " << t << "\n";
The output is:
的输出是:
sec: 1474116832
min: 32767
hour: 4238231
day: 27
month: 5
year: 110
sec: 52
min: 0
hour: 6
day: 2
month: 9
year: 640
time: 18008625652 (Fri, 02 Sep 2540 04:00:52 GMT)
My question is why does mktime()
change the values of time
and why is the converted time_t
not equal to my input date. I would expect that the output is the date expressed in seconds since 1970 (27.05.2010 = 1330905600).
我的问题是为什么mktime()会改变时间的值,为什么转换后的time_t不等于输入日期。我希望输出是自1970年以来的秒数(27.05.2010 = 1330905600)。
Thanks in advance
谢谢提前
1 个解决方案
#1
6
mktime
normalizes all its arguments before converting to a time_t
. You have huge values for hour, minute and second, so those are all converted into appropriate numbers of days, pushing the value far into the future.
在转换到time_t之前,mktime将所有参数规范化。你有一小时、一分一秒的巨大价值,所以这些都转化成适当的天数,把价值推到未来。
You need to zero out the other important attributes (including hour/minute/second) of the tm
before calling mktime
. As noted in a comment just initialize it to zero: tm time = {0};
(tagged C++ so the leading struct
isn't needed). Further note that you may wish to set tm_isdst
to -1 so that it attempts to determine the daylight saving value rather than assuming not DST (if initialized to zero).
在调用mktime之前,您需要将tm的其他重要属性(包括小时/分钟/秒)排除掉。正如注释中所指出的,将其初始化为0:tm time = {0};(标记为c++,所以不需要引导结构)。还要注意,您可能希望将tm_isdst设置为-1,以便它尝试确定夏令时值,而不是假设DST(如果初始化为0)。
#1
6
mktime
normalizes all its arguments before converting to a time_t
. You have huge values for hour, minute and second, so those are all converted into appropriate numbers of days, pushing the value far into the future.
在转换到time_t之前,mktime将所有参数规范化。你有一小时、一分一秒的巨大价值,所以这些都转化成适当的天数,把价值推到未来。
You need to zero out the other important attributes (including hour/minute/second) of the tm
before calling mktime
. As noted in a comment just initialize it to zero: tm time = {0};
(tagged C++ so the leading struct
isn't needed). Further note that you may wish to set tm_isdst
to -1 so that it attempts to determine the daylight saving value rather than assuming not DST (if initialized to zero).
在调用mktime之前,您需要将tm的其他重要属性(包括小时/分钟/秒)排除掉。正如注释中所指出的,将其初始化为0:tm time = {0};(标记为c++,所以不需要引导结构)。还要注意,您可能希望将tm_isdst设置为-1,以便它尝试确定夏令时值,而不是假设DST(如果初始化为0)。