What is the right way to convert into UNIX timestamp from the date and time in C/C++?

c, c++, date, datetime, unix-timestamp

Solution

POSIX has a formula for exactly what you want:

http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_15

tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
    (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
    ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400

This works whenever you have a broken-down time in GMT, even if the underlying system's `mktime`, etc. functions do not use the same format `time_t` as "Unix timestamps".

If your original time is in local time, you can use `mktime` and `gmtime` to convert it to GMT using the system's notion of timezone rules. If you want to apply your own timezone offset rules, just do that manually before using the above formula.

Problem

I have a lot of dates with time in this format: ``` day.mon.year - hour:min:sec ``` And I need to convert this dates with time into Unix timestamp. I used tm structure, but I can't fill those fields: ``` tm_wday tm_yday ``` And I don't must I fill those field, because I don't know do this field have any effect to the value of Unix timestamp. Help me to choose rigth way to calculate Unix timestamp. P.S. Dates with time aren't current, they can be date of the 20-th century or future dates (to 2038 year). P.P.S. I use OS Windows.

Original source