Conversion of String Time to time_t
Converting a string containing time in "hh:mm:ss" format to time_t in C can be achieved in various ways.
One method is to leverage C 11's advanced time and date manipulation capabilities with
For example:
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 = std::mktime(&tm);
Comparing Time Variables for Earliest Value
To compare two strings containing time, you can either compare their corresponding time_t representations or use string comparison techniques.
Using time_t values, you can directly compare them using std::less. For example:
std::string curr_time = "18:35:21"; std::string user_time = "22:45:31"; std::istringstream ss_curr(curr_time); std::istringstream ss_user(user_time); std::tm tm_curr, tm_user; ss_curr >> std::get_time(&tm_curr, "%H:%M:%S"); ss_user >> std::get_time(&tm_user, "%H:%M:%S"); std::time_t time_curr = std::mktime(&tm_curr); std::time_t time_user = std::mktime(&tm_user); if (time_curr < time_user) { std::cout << curr_time << " is earlier than " << user_time << std::endl; } else { std::cout << user_time << " is earlier than " << curr_time << std::endl; }
Alternatively, string comparison can be used, assuming both times are in the same format:
if (curr_time < user_time) { std::cout << curr_time << " is earlier than " << user_time << std::endl; } else { std::cout << user_time << " is earlier than " << curr_time << std::endl; }
The above is the detailed content of How to Determine the Earlier Time Between Two String Time Values in C ?. For more information, please follow other related articles on the PHP Chinese website!