Is there a good equivalent implementation of strptime()
available for Windows? Unfortunately, this POSIX function does not appear to be available.
Open Group description of strptime - summary: it converts a text string such as "MM-DD-YYYY HH:MM:SS"
into a tm struct
, the opposite of strftime()
.
Description. The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. The format contains zero or more directives.
strptime() -> string parsed time.
If you don't want to port any code or condemn your project to boost, you can do this:
sscanf
struct tm
(subtract 1 from month and 1900 from year -- months are 0-11 and years start in 1900)mktime
to get a UTC epoch integerJust remember to set the isdst
member of the struct tm
to -1, or else you'll have daylight savings issues.
Assuming you are using Visual Studio 2015 or above, you can use this as a drop-in replacement for strptime:
#include <time.h> #include <iomanip> #include <sstream> extern "C" char* strptime(const char* s, const char* f, struct tm* tm) { // Isn't the C++ standard lib nice? std::get_time is defined such that its // format parameters are the exact same as strptime. Of course, we have to // create a string stream first, and imbue it with the current C locale, and // we also have to make sure we return the right things if it fails, or // if it succeeds, but this is still far simpler an implementation than any // of the versions in any of the C standard libraries. std::istringstream input(s); input.imbue(std::locale(setlocale(LC_ALL, nullptr))); input >> std::get_time(tm, f); if (input.fail()) { return nullptr; } return (char*)(s + input.tellg()); }
Just be aware that for cross platform applications, std::get_time
wasn't implemented until GCC 5.1, so switching to calling std::get_time
directly may not be an option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With