如何将包含时间的字符串变量转换为 C++ 中的 time_t 类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11213326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a string variable containing time to time_t type in c++?
提问by R11G
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"
我有一个包含hh:mm:ss 格式时间的字符串变量。如何将其转换为 time_t 类型?例如:字符串 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"
另外,如何比较两个包含时间的变量以确定哪个是最早的?例如:string curr_time = "18:35:21" string user_time = "22:45:31"
回答by v2blz
With C++11 you can now do
使用 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);
see std::get_timeand strftimefor reference
请参阅std::get_time和strftime以供参考
回答by Adam Rosenfield
You can use strptime(3)
to parse the time, and then mktime(3)
to convert it to a time_t
:
您可以使用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
回答by Mahmoud Al-Qudsi
This should work:
这应该有效:
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);
Modify as needed.
根据需要进行修改。