C++ How can I convert a date in year-month-day format to a unix epoch format?
I need to convert a given date to an int containing the number of milliseconds since Jan 1 1970. (unix epoch)
I tried the following code:
tm lDate;
lDate.tm_sec = 0;
lDate.tm_min = 0;
lDate.tm_hour = 0;
lDate.tm_mday = 1;
lDate.tm_mon = 10;
lDate.tm_year = 2010 - 1900;
time_t lTimeEpoch = mktime(&lDate);
cout << "Epoch: " << lTimeEpoch << endl;
The result is Epoch: 1288584000 which corresponds to Mon, 01 Nov 2010 04:00:00 GMT
Edit: I was expecting Oct 01 2010, apparently tm_mon is the number of months SINCE January, so the correct line would be lDate.开发者_如何学Pythontm_mon = 10 -1;
As specified in the man page, tm_mon is: The number of months since January, in the range 0 to 11.
You are likely getting confused by timezones. I think you're missing this, from the man page:
The
mktime()
function converts a broken-down time structure, expressed as local time...
精彩评论