When working with time data in C , it's often necessary to convert strings containing time in the "hh:mm:ss" format to the time_t type. Here's how you can achieve this:
#include <iostream> #include <iomanip> #include <sstream> #include <ctime> int main() { std::string time_details = "16:35:12"; struct std::tm tm; std::istringstream ss(time_details); ss >> std::get_time(&tm, "%H:%M:%S"); // or use "%T" for this case std::time_t time_value = std::mktime(&tm); std::cout << "Converted time: " << std::put_time(std::gmtime(&time_value), "%H:%M:%S") << '\n'; return 0; }
This code demonstrates:
Comparing Time Variables: To compare two time_t variables (e.g., curr_time and user_time), you can use the following method:
if (curr_time < user_time) { std::cout << "curr_time is earlier than user_time.\n"; } else if (curr_time == user_time) { std::cout << "curr_time and user_time are the same.\n"; } else { std::cout << "user_time is earlier than curr_time.\n"; }
The above is the detailed content of How to Convert a String Time to time_t in C ?. For more information, please follow other related articles on the PHP Chinese website!