C++从具有不同时区的字符串中解析日期时间

标签 c++ datetime c++11

如何从不同时区的字符串中解析日期时间?我有简单字符串形式的日期和时间,例如 2011-01-15 04:01:00,它们来自纽约时区(东部:UTC -5/-4)。我编写了下面的代码,但它会自动将时区转换为我的本地时区。

是否可以在不使用任何额外的 C++ 11 库(例如 Boost)的情况下完成此操作,以免给非常简单的操作增加复杂性?如果没有,使用 Boost 的示例会很好。

我在 Windows 8.1 上使用 Visual Studio 2013。

#include <ctime>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
    vector<string> datetimes{ "2011-01-15 04:01:00",
                              "2014-06-07 23:17:00",
                              "2015-11-29 14:55:00" };

    for (auto i : datetimes)
    {
        stringstream ss1(i);
        tm tm;
        ss1 >> get_time(&tm, "%Y-%m-%d %H:%M:%S");
        stringstream ss2;
        ss2 << put_time(&tm, "%c %Z");
        cout << ss2.str() << endl;
    }
}

输出:

01/15/11 04:01:00 Russia TZ 2 Daylight Time
06/07/14 23:17:00 Russia TZ 2 Daylight Time
11/29/15 14:55:00 Russia TZ 2 Daylight Time

但我需要输出如下:

01/15/11 04:01:00 New York / Eastern (or whatever right name)
06/07/14 23:17:00 New York
11/29/15 14:55:00 New York

最佳答案

只需使用 boost 即可。严重地。以下是一些示例代码:

using namespace boost::posix_time;
using namespace boost::gregorian;

//eastern timezone is utc-5
typedef boost::date_time::local_adjustor<ptime, -5, us_dst> us_eastern;

ptime t1(date(2001,Dec,31), hours(19)); //5 hours b/f midnight NY time

ptime t2 =  us_eastern::local_to_utc(t1); // t2 is now in utc

std::cout << to_simple_string(t1) << " in New York is " 
          << to_simple_string(t2) << " UTC time "
          << std::endl

示例代码取自http://www.boost.org/doc/libs/1_42_0/doc/html/date_time/examples.html并根据可读性和简洁性进行调整,同时仍然回答问题。

无论您采用什么解决方案,请确保您永远不会手动减去时区转换或类似的内容。在某种程度上,您需要使用库。这个东西充满了陷阱,而且非常复杂,所以不管涉及多少工作或不涉及多少工作,如果你自己做的话几乎肯定是不对的。

关于C++从具有不同时区的字符串中解析日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30902127/

相关文章:

c++ - 无法从文件中读取

c# - 如何合并日期时间类型字段和浮点类型字段。之后解析为日期时间数据类型字段(daypilot 日历)

json - Powershell 7.2 : ConvertFrom-Json - Date Handling

C++ 模板,将 enable_if 用于运算符的两种不同实现

在带有 VS2012/w Update 3 的 Windows 7 上构建的 C++ 程序无法在 WinXP SP3 上运行

c++ - 如何在 Win32 上读取 wchar_t 缓冲区中的整个文件?

c++ - 是否可以让指针指向第一个指针指向的变量?

c# - DateTime空值

c++ - 即使模板函数在任何地方都没有调用,static_assert 也无法编译

c++ - 仅为基本数据类型制作模板