【问题标题】:how to parse a string with date-time + time offset to a boost::posix_time::ptime?如何将具有日期时间+时间偏移的字符串解析为 boost::posix_time::ptime?
【发布时间】:2011-12-09 20:05:49
【问题描述】:

我有一个字符串“2011-10-20T09:30:10-05:00”

有人知道我如何使用 boost::date_time 库解析它吗?

【问题讨论】:

    标签: c++ boost boost-date-time


    【解决方案1】:

    好的,我找到答案了

    代码(用于 VS)

    它将字符串转换为 local_date_time,但对我来说这是可以接受的:

    #pragma warning(push)
    #pragma warning(disable:4244)
    #pragma warning(disable:4245)
    #include <boost/date_time/local_time/local_time.hpp>
    #pragma warning(pop)
    
    #include <iostream>
    #include <string>
    
    int main() 
    {
        using namespace std;
        using namespace boost::local_time;
    
        istringstream ss("2011-10-20T09:30:10-05:00");
        ss.exceptions(ios_base::failbit);
        local_time_input_facet* facet = new local_time_input_facet("%Y-%m-%dT%H:%M:%S%ZP");
        ss.imbue(locale(ss.getloc(), facet));
    
        local_date_time ldt(not_a_date_time);
        ss >> ldt; // do the parse
    
        std::cout <<
            ldt.to_string() <<
            "\noffset is: " <<
            to_simple_string(ldt.zone()->base_utc_offset()) <<
            std::endl;
    }
    

    也许有人会需要它

    【讨论】:

    • 您确定有泄漏吗?我不记得细节了,但其他例子也没有删除指针——也许它在其他类中被删除了?
    • @flyx “语言环境负责从它自己的析构函数中调用匹配的删除。” - 来自en.cppreference.com/w/cpp/locale/locale/locale ..
    • @flyx 大声笑这不是泄漏, imbue 方法取得了方面的所有权。在诋毁他人之前,您应该了解标准 C++ 库吗?
    【解决方案2】:
    const char *s = "2011-10-20T09:30:10-05:00";
    
    boost::posix_time::ptime t_local(
        boost::gregorian::from_string(std::string(s, s + 10)),
        boost::posix_time::duration_from_string(std::string(s + 11, s + 19))
    );
    
    boost::posix_time::ptime t(
        t_local - boost::posix_time::duration_from_string(std::string(s + 19, s + 25))
    );
    

    现在t 是UTC 时间,t_local 是当地时间。

    【讨论】:

    • @Alek86 是的,我确实建议这样做。这些幻数是ISO-8601 格式化日期字符串的不变索引,它们不会改变。当然,您应该在生产代码中添加对字符串长度等的错误检查。此代码是一个概念验证示例。
    • t_local 的持续时间是否应该从 't' 中减去
    • @J.Churchill 我不这么认为......考虑一下:美国东部时间是 UTC-05:00。如果现在是格林威治的中午,则加上 -05:00,所以现在是纽约的上午 07:00。所以,健全性检查通过了。
    • 如果目标是获取 UTC 时间,则应该减去它。在上面 2011-10-20T09:30:10-05:00 的例子中,指定的时间 is 9:30:10am Eastern Time,所以 talready 是本地的时间。然后t_local 将是更西边的五个时区。
    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2015-01-10
    • 2010-11-13
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多