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

将Epoch时间转换为标准日期时间时遇类型转换错误求助

解决Epoch字符串转time_t的类型转换问题

这个错误很典型——你直接把std::string类型的Epoch时间字符串赋值给time_t变量了,但time_t本质是一个数值类型(通常是整数),两者之间没有默认的转换规则,所以编译器抛出了类型不匹配的错误。

核心解决思路

你需要先把字符串形式的Epoch时间转换成整数,再赋值给time_t。因为Epoch时间(比如1522516475)可能超出普通int的范围,建议用long long来中转,再安全转换为time_t。

修正后的完整代码示例

#include <string>
#include <stdexcept>
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

// 获取JSON中的Epoch时间字符串
const std::string time_str = jsonData["data"]["table"][i]["data"]["created_utc"].asString(); 

try {
    // 将字符串转换为long long类型的Epoch数值
    long long epoch_val = std::stoll(time_str);
    // 安全转换为time_t类型
    std::time_t btime_ = static_cast<std::time_t>(epoch_val);
    
    // 使用Boost库转换为可读时间并输出
    std::cout << boost::posix_time::from_time_t(btime_) << std::endl;
    // 后续的区域设置代码可以正常保留
    std::cout.imbue(std::locale(...));
} catch (const std::invalid_argument& e) {
    // 处理字符串不是合法数字的异常情况
    std::cerr << "无效的Epoch时间字符串: " << e.what() << std::endl;
} catch (const std::out_of_range& e) {
    // 处理数值超出类型范围的异常情况
    std::cerr << "Epoch时间值超出范围: " << e.what() << std::endl;
}

补充说明

  • 如果你的编译器版本较旧不支持std::stoll,可以用std::strtol或者boost::lexical_cast<long long>(time_str)替代字符串转整数的步骤。
  • 加上异常处理很关键,能避免JSON返回非法格式字符串时导致程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:56:46