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++?
views:
3347answers:
4
+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
2008-11-26 19:12:14
+5
A:
Use strptime()
to parse the time into a struct tm
, then use mktime()
to convert to a time_t
.
Robert Gamble
2008-11-26 19:12:36
strptime() doesn't appear to be available on Windows. Is there a good alternative?
Andrew
2008-11-26 19:17:15
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
2008-11-26 19:23:46
+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