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

如何从std::chrono::time_point提取时分秒?代码小时值异常排查

问题根源

你代码里获取的是从1970年1月1日00:00:00 UTC到当前时刻的总小时数,不是当天的小时值,所以数值会大得离谱,这就是核心问题。

正确提取时分秒的方法

要拿到当天的时、分、秒,需要把time_point转换成人类可读的时间结构,以下是两种实用方案:

方案一:兼容C++11及以上的标准写法

#include <chrono>
#include <iostream>
#include <ctime>

int main() {
    // 定义目标类型的time_point
    std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp = 
        std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());

    // 将time_point转换为C标准库的time_t类型
    std::time_t tt = std::chrono::system_clock::to_time_t(tp);

    // 转换为当地时间的tm结构体(用gmtime则获取UTC时间)
    std::tm local_tm = *std::localtime(&tt);

    // 提取时分秒
    int hours = local_tm.tm_hour;
    int minutes = local_tm.tm_min;
    int seconds = local_tm.tm_sec;

    std::cout << "Hours: " << hours << std::endl;
    std::cout << "Minutes: " << minutes << std::endl;
    std::cout << "Seconds: " << seconds << std::endl;

    return 0;
}

注意:std::localtime不是线程安全的,多线程环境下建议用平台特定安全版本:Windows用localtime_s,Linux/macOS用localtime_r

方案二:C++20及以上的简化写法

如果编译器支持C++20,可直接用std::chrono的新工具拆分时间:

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    time_point<system_clock, milliseconds> tp = time_point_cast<milliseconds>(system_clock::now());

    // 计算从当天午夜到当前时刻的时长
    auto today = floor<days>(tp);
    auto hms = hh_mm_ss(tp - today);

    std::cout << "Hours: " << hms.hours().count() << std::endl;
    std::cout << "Minutes: " << hms.minutes().count() << std::endl;
    std::cout << "Seconds: " << hms.seconds().count() << std::endl;
    // 还能直接获取毫秒:hms.subseconds().count()

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:32:14