我有一个包含时间的字符串变量,格式为hh:mm:ss.如何将其转换为time_t类型?例如:string time_details ="16:35:12"
另外,如何比较包含时间的两个变量,以便确定哪个是最早的?例如:string curr_time ="18:35:21"string user_time ="22:45:31"
Ada*_*eld 50
您可以使用strptime(3)解析时间,然后mktime(3)将其转换为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
Run Code Online (Sandbox Code Playgroud)
v2b*_*blz 49
使用C++ 11,您现在可以做到
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);
Run Code Online (Sandbox Code Playgroud)
请参阅std :: get_time和strftime以供参考
Mah*_*dsi 16
这应该工作:
int hh, mm, ss;
struct tm when = {0};
sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);
when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;
time_t converted;
converted = mktime(&when);
Run Code Online (Sandbox Code Playgroud)
根据需要修改.