如何在 C 中将表示时间的字符串转换为'time_t”?
Nov 10, 2024 am 07:41 AM将表示时间的字符串转换为 C 中的 time_t
在 C 中处理时间时,您可能会遇到这样的情况:您有一个字符串表示特定时间,需要将其转换为可移植的 time_t 数据类型。 time_t 类型表示自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的秒数。
转换为 time_t
在 C 11 及更高版本中,std::get_time 函数可用于将字符串解析为 std::tm 结构,然后可以将其转换为 time_t 使用 mktime:
#include <iostream> #include <sstream> #include <time.h> int main() { std::string time_details = "16:35:12"; std::tm tm; std::istringstream ss(time_details); ss >> std::get_time(&tm, "%H:%M:%S"); std::time_t time = mktime(&tm); // Print the converted time_t std::cout << "Converted time: " << time << std::endl; return 0; }
登录后复制
比较两次
一旦您在 time_t 中有多个时间格式,您可以比较它们以确定哪个较早。
#include <iostream> #include <time.h> int main() { std::string curr_time = "18:35:21"; // Current time std::string user_time = "22:45:31"; // User's time std::tm curr_tm, user_tm; std::istringstream ss; // Parse both times ss.str(curr_time); ss >> std::get_time(&curr_tm, "%H:%M:%S"); ss.clear(); ss.str(user_time); ss >> std::get_time(&user_tm, "%H:%M:%S"); // Compare the time_t values std::time_t curr_secs = mktime(&curr_tm); std::time_t user_secs = mktime(&user_tm); if (curr_secs < user_secs) { std::cout << "Current time is earlier than user's time" << std::endl; } else { std::cout << "User's time is earlier than current time" << std::endl; } return 0; }
登录后复制
以上是如何在 C 中将表示时间的字符串转换为'time_t”?的详细内容。更多信息请关注PHP中文网其他相关文章!
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门文章
击败分裂小说需要多长时间?
3 周前
By DDD
仓库:如何复兴队友
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前
By 尊渡假赌尊渡假赌尊渡假赌
公众号网页更新缓存难题:如何避免版本更新后旧缓存影响用户体验?
3 周前
By 王林

热门文章
击败分裂小说需要多长时间?
3 周前
By DDD
仓库:如何复兴队友
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前
By 尊渡假赌尊渡假赌尊渡假赌
公众号网页更新缓存难题:如何避免版本更新后旧缓存影响用户体验?
3 周前
By 王林

热门文章标签

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)