【问题标题】:C++ library (unix) to parse date/time string Including timezones用于解析日期/时间字符串的 C++ 库 (unix) 包括时区
【发布时间】:2010-08-23 12:30:23
【问题描述】:

我有多种格式的日期。 现在我想在 c++ 中有一个函数(来自某个库),它可以解析这些日期/时间字符串并给我一些像 tm 这样的结构或将它们转换为一些确定性表示,以便我可以玩弄日期/时间。

我看到的一些格式如下: 2008 年 2 月 19 日星期二 20:47:53 +0530 2009 年 4 月 28 日星期二 18:22:39 -0700 (PDT)

我可以做没有时区的那些,但对于那些有时区的,我基本上需要库将其转换为 tm 结构中的 UTC。

我尝试过 boost 和 strptime,但据我所知,两者都不支持输入时区。有什么我错过的吗?

非常感谢您对此提供任何帮助。

问候

【问题讨论】:

标签: c++ datetime


【解决方案1】:

您可以使用 boost 来做到这一点,但它对输入字符串中时区的格式有点特别。它必须在POSIX time zone format

例如:

#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。

【讨论】:

    【解决方案2】:

    如果你有很多格式要处理,我建议你看看ICU:http://site.icu-project.org/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      相关资源
      最近更新 更多