views:

3347

answers:

4

What's the best way to convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t value in either C or C++?

+1  A: 

I'm afraid there isn't any in Standard C / C++ . There is the POSIX function strptime which can convert to struct tm, which can then be converted to time_t using mktime.

If you are aiming for cross platform compatibility, better use boost::date_time, which has sophisticated functions for this.

Johannes Schaub - litb
+5  A: 

Use strptime() to parse the time into a struct tm, then use mktime() to convert to a time_t.

Robert Gamble
strptime() doesn't appear to be available on Windows. Is there a good alternative?
Andrew
Don't know if a good alternative on Windows, there are several open source implementations floating around that you could use. Alternatively, if you know the date will always be in the format you provided, you can parse it into a struct tm, perhaps using sscanf, and then use mktime to get a time_t.
Robert Gamble
+2  A: 

Boost's date time library should help; in particular you might want to look at http://www.boost.org/doc/libs/1_37_0/doc/html/date_time/date_time_io.html

+2  A: 

In the absence of strptime you could use sscanf to parse the data into a struct tm and then call mktime. Not the most elegant solution but it would work.

Rob
Thanks Rob... nice pic btw.
Andrew