我有以下代码:
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";
输出结果为:
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)
我的问题是为什么mktime()
会更改time
的值以及为什么转换的time_t
不等于我的输入日期。我希望输出是自1970年以来以秒为单位表示的日期(2010年5月27日= 1330905600)。
提前致谢
答案 0 :(得分:8)
mktime
在转换为time_t
之前对其所有参数进行规范化。你有小时,分钟和秒的巨大价值,所以这些都被转换成适当的天数,将价值推向了未来。
在调用tm
之前,您需要将mktime
的其他重要属性(包括小时/分钟/秒)清零。正如注释中所述,只需将其初始化为零:tm time = {0};
(标记为C ++,因此不需要前导struct
)。另请注意,您可能希望将tm_isdst
设置为-1,以便它尝试确定夏令时值,而不是假定不是DST(如果初始化为零)。