grouleau
grouleau

Reputation: 23

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.tm_mon = 10 -1;

Upvotes: 2

Views: 4282

Answers (2)

Benoit Thiery
Benoit Thiery

Reputation: 6387

As specified in the man page, tm_mon is: The number of months since January, in the range 0 to 11.

Upvotes: 2

Thanatos
Thanatos

Reputation: 44364

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...

Upvotes: 0

Related Questions