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

使用Boost::posix_time::time_from_string函数遇转换异常问题

解决boost::posix_time::time_from_string解析失败的问题

嘿,我一眼就看出问题出在哪了——你用错了对应的解析函数!

问题根源

to_iso_string(t1)生成的是ISO格式的时间字符串,比如20240520T143025.123456,而time_from_string函数并不支持这种格式,它期望的是带连字符、空格分隔的格式(比如2024-05-20 14:30:25.123456),格式不匹配直接导致了 lexical cast 失败。

两种解决方案

方案1:用对应ISO格式的解析函数

Boost专门提供了from_iso_string来解析to_iso_string生成的字符串,直接替换即可:

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
int main() {
    using namespace boost::posix_time;
    cout << "Getting t1" << endl;
    ptime t1 = microsec_clock::universal_time();
    cout << "Getting t1 OK" << endl;
    cout << "Getting t2" << endl;
    // 替换为适配ISO格式的解析函数
    ptime t2 = from_iso_string(to_iso_string(t1));
    cout << "Getting t2 OK" << endl;
    // 可以验证两个时间是否一致
    cout << "t1: " << to_iso_string(t1) << endl;
    cout << "t2: " << to_iso_string(t2) << endl;
}

方案2:改用匹配time_from_string的字符串生成函数

如果你一定要保留time_from_string,可以把to_iso_string换成to_simple_string——它生成的格式刚好是time_from_string支持的:

ptime t2 = time_from_string(to_simple_string(t1));

验证结果

修改后运行代码,你会看到程序正常执行:

Getting t1
Getting t1 OK
Getting t2
Getting t2 OK
t1: 20240520T143025.123456
t2: 20240520T143025.123456

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:02:19