Date/time conversion: string representation to time_t [closed]

How do I convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t value in either C or C++?


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


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.


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


Note that strptime mentioned in accepted answer is not portable. Here's handy C++11 code I use to convert string to std::time_t :

static std::time_t to_time_t(const std::string& str, bool is_dst = false, const std::string& format = "%Y-%b-%d %H:%M:%S")
{
    std::tm t = {0};
    t.tm_isdst = is_dst ? 1 : 0;
    std::istringstream ss(str);
    ss >> std::get_time(&t, format.c_str());
    return mktime(&t);
}

You can call it like this:

std::time_t t = to_time_t("2018-February-12 23:12:34");

You can find string format parameters here.