C++库(Unix)用于解析日期/时间字符串,包括时区

5
我有许多不同格式的日期。现在我想要一个函数(从某个库中)来解析这些日期/时间字符串,并给我一个结构,如tm,或将它们转换为一些确定性表示,以便我可以操作日期/时间。
我看到的一些格式如下: Tue, 19 Feb 2008 20:47:53 +0530 Tue, 28 Apr 2009 18:22:39 -0700 (PDT)
我能够处理没有时区的日期,但对于带有时区的日期,我需要库将其转换为UTC并放入tm结构中。
我已经尝试过boost和strptime,但据我所知,两者都不支持输入时区。我错过了什么吗?
对此的任何帮助将不胜感激。
谢谢!

尝试使用 locale 吗?http://www.cplusplus.com/reference/std/locale/ - DumbCoder
2个回答

2
你可以使用boost完成这个任务,但输入字符串中的时区格式需要特别注意。它必须符合POSIX时区格式

例如:

#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/time_facet.hpp>
int main()
{
       std::string msg = "28 Apr 2009 18:22:39 PST-8PDT,M4.1.0,M10.1.0"; // or just "PDT-7" but that will be a new, fake time zone called 'PDT'

       std::istringstream ss(msg);
       ss.imbue( std::locale(ss.getloc(),
                 new boost::local_time::local_time_input_facet("%d %b %Y %H:%M:%S%F %ZP")));
       boost::local_time::local_date_time t(boost::date_time::pos_infin);
       ss >> t;
       std::cout << t << '\n';
       // and now you can call t.to_tm() to get your tm structure
}

我建议添加一些预处理步骤,将你的时区格式转换为posix格式,然后将字符串传递给boost。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接