How to convert a string variable containing time to time_t type in c++?
I have a string variable containing time in hh:mm:ss format. How to convert it into time_t type? eg: string time_details = "16:35:12"
Also, how to compare two variables containing time so as to decide which is the earliest? eg : string curr_time = "18:35:21" string user_time = "22:45:31"
With C++11 you can now do
struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);
see std::get_time and strftime for reference
You can use strptime(3)
to parse the time, and then mktime(3)
to convert it to a time_t
:
const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm); // t is now your desired time_t