You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C++ chrono库比较日期字符串与当前系统时间

C++ chrono日期比较实现方案

核心实现逻辑

你需要将系统当前时间和待匹配的日期字符串统一转为相同的时间格式后再进行比较,可根据需求选择精确匹配到秒或仅匹配年月日两种匹配规则。

修正后可运行代码

方案1:精确匹配到秒(日期+时分秒完全一致时触发任务)

#include <iostream>
#include <chrono> 
#include <ctime>
#include <cstring>
using namespace std;

int main(){
    // 1. 获取当前系统时间并转为tm结构体
    auto end = chrono::system_clock::now();
    time_t end_time = chrono::system_clock::to_time_t(end);
    // localtime转为本地时区,需UTC时区可替换为gmtime
    tm current_tm = *localtime(&end_time); 

    // 2. 解析待匹配的日期字符串为tm结构体
    string date_to_do_something ="Tue Jul 27 17:13:17 2021";  
    tm target_tm{};
    // 格式化字符串需和输入日期格式完全对应
    strptime(date_to_do_something.c_str(), "%a %b %d %H:%M:%S %Y", &target_tm);
    time_t target_time = mktime(&target_tm);

    // 3. 比较时间是否相等
    if (difftime(end_time, target_time) == 0) {
        cout << "时间匹配,触发对应操作" << endl;
    } else {
        cout << "时间不匹配" << endl;
    }
    
    return 0;
}

方案2:仅匹配年月日(当天任意时间都触发任务)

只需在比较前将两个时间的时分秒统一置0即可:

// 省略前序获取current_tm、target_tm的代码
current_tm.tm_hour = 0;
current_tm.tm_min = 0;
current_tm.tm_sec = 0;
target_tm.tm_hour = 0;
target_tm.tm_min = 0;
target_tm.tm_sec = 0;

time_t current_date = mktime(&current_tm);
time_t target_date = mktime(&target_tm);
if (difftime(current_date, target_date) == 0) {
    cout << "日期匹配,触发对应操作" << endl;
}

常见问题说明

  • 你代码中输出的奇怪类型Pc是char*的缩写(对应ctime的返回值类型),Pl是long*的缩写(对应time_t指针的类型,绝大多数系统下time_t为long类型),属于正常输出。
  • Windows平台原生不提供strptime函数,可替换为C++20的std::chrono::parse实现跨平台解析,或手动用sscanf拆分字符串填充tm结构体。
  • 比较时间差使用difftime可规避不同系统下time_t的精度差异问题,比直接用==比较更稳妥。

内容的提问来源于stack exchange,提问作者Lordoftherings

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 19:54:03