问题
I use mktime
to create a unix timestamp from my current local time:
#include <time.h>
int _tmain(int argc, _TCHAR* argv[])
{
struct tm info;
// 16.05.2014
info.tm_mday = 16;
info.tm_mon = 5;
info.tm_year = 114; // Years since 1900
// 08:00:00 Uhr
info.tm_hour = 8;
info.tm_min = 0;
info.tm_sec = 0;
// Convert to Unix timestamp
info.tm_isdst = -1;
time_t timestamp = mktime(&info);
printf("Timestamp: %i", timestamp);
}
This gives me:
1402898400
When converting this back to a human readable time (via some website) this translates to:
16.06.2014 08:00:00
As you can see this is one month off from what I expected (put in May (5), got out June (6)). Why?
回答1:
C11 7.27.1 Components of time
int tm_sec; // seconds after the minute — [0, 60] int tm_min; // minutes after the hour — [0, 59] int tm_hour; // hours since midnight — [0, 23] int tm_mday; // day of the month — [1, 31] int tm_mon; // months since January — [0, 11] int tm_year; // years since 1900 int tm_wday; // days since Sunday — [0, 6] int tm_yday; // days since January 1 — [0, 365] int tm_isdst; // Daylight Saving Time flag
tm_mon
starts with 0
, not 1
. So the value of 5
means it's June, not May.
来源:https://stackoverflow.com/questions/23693669/mktime-returns-wrong-timestamp-off-by-a-whole-month