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

新手上路,请多包涵

我有一个字符串变量,其中包含 hh:mm:ss 格式 的时间。如何将其转换为 time_t 类型?例如:字符串 time_details = “16:35:12”

另外,如何比较两个包含时间的变量,以确定哪个是最早的?例如:字符串 curr_time = “18:35:21” 字符串 user_time = “22:45:31”

原文由 R11G 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 358
2 个回答

您可以使用 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

原文由 Adam Rosenfield 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 strptime

 struct tm tm;
memset(&tm, 0, sizeof(tm));
char *res = strptime(strtime.c_str(), format.c_str(), &tm);
if (res == nullptr) {
    // err process
}
ti = mktime(&tm);

必须初始化tm,并检查返回值。

原文由 selfboot 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题