C++中如何判断当前时间是否早于配置的指定时间?
C++ 判断当前时间是否早于指定时刻的最优实现
你想要的「构造指定时间对象直接和当前时间比较」的需求,根据使用的C++标准版本,可以选择两种实现方案:
C++20 及以上版本(最优方案)
C++20 扩展了std::chrono库的日历和时间功能,原生支持时刻构造与直接比较,不需要转换任何C风格的时间类型,代码简洁且类型安全:
#include <chrono> #include <iostream> int main() { // 构造目标时刻 14:32 constexpr std::chrono::hh_mm_ss target{std::chrono::hours(14) + std::chrono::minutes(32)}; // 获取当前UTC时间的当日时分秒 const auto now = std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now()); const auto utc_now = std::chrono::utc_time<std::chrono::seconds>{now}; const std::chrono::hh_mm_ss now_tod{utc_now - std::chrono::floor<std::chrono::days>(utc_now)}; // 直接比较两个时刻对象 if (now_tod < target) { std::cout << "It's before 14:32\n"; } return 0; }
如果需要判断本地时间,把代码中的std::chrono::utc_time替换为std::chrono::local_time即可。
C++11/17 兼容方案
如果项目暂时不支持C++20,可以将现有逻辑封装为通用工具函数,减少重复代码:
#include <chrono> #include <ctime> #include <iostream> // 判断当前UTC时间是否早于 target_hour:target_min bool is_before_target(int target_hour, int target_min) { const auto now = std::chrono::system_clock::now(); const std::time_t tt = std::chrono::system_clock::to_time_t(now); const std::tm utc_tm = *gmtime(&tt); return utc_tm.tm_hour < target_hour || (utc_tm.tm_hour == target_hour && utc_tm.tm_min < target_min); } int main() { if (is_before_target(14, 32)) { std::cout << "It's before 14:32\n"; } return 0; }
注意事项
- 若需要判断本地时间,把
gmtime替换为localtime即可 - C++20方案不存在部分平台
gmtime/localtime非线程安全的问题,稳定性更高 - 两种实现默认都是判断当日的时刻比较,不需要额外处理跨天逻辑
内容的提问来源于stack exchange,提问作者Joshua Segal
相关产品推荐
相关产品推荐

