如何在c ++中将包含time的字符串变量转换为time_t类型?

R11*_*11G 33 c++ time

我有一个包含时间的字符串变量,格式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)

  • @KyleStrand:它是POSIX.1-2001(以及SUSv2)的一部分.你是对的,它不是标准的C或C++,但它不仅仅是Linux. (3认同)
  • 我相信,`strptime`是特定于Linux的。 (2认同)

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_timestrftime以供参考

  • 我认为值得一提的是 std::get_time **在 GCC 版本 5 中可用**,然后你需要 `#include <iomanip>` (2认同)
  • `std::get_time` 在 VS2013 下也有一些错误,例如这里 http://stackoverflow.com/questions/32019209/is-this-a-bug-in-stdget-time 和这里​​ http://stackoverflow.com/questions /35041344/trying-to-use-stdget-time-to-parse-yymmdd-and-failing (2认同)

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)

根据需要修改.

  • 这段代码可以得到时间,但**date**(yyyy-MM-dd)怎么样? (3认同)