C++ c++;从具有不同时区的字符串分析datetime
如何从不同时区的字符串中解析datetime?我用简单的字符串表示日期和时间,如C++ c++;从具有不同时区的字符串分析datetime,c++,datetime,c++11,C++,Datetime,C++11,如何从不同时区的字符串中解析datetime?我用简单的字符串表示日期和时间,如2011-01-15 04:01:00,它们来自纽约时区(东部:UTC-5/-4)。我写了下面的代码,但它会自动将时区转换为本地时区 是否有可能在没有任何额外的C++ 11库(如Boost)的情况下,不增加复杂操作的复杂性?如果不是的话,举一个Boost的例子就好了 我在Windows 8.1上使用Visual Studio 2013 #include <ctime> #include <strin
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 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
使用名称空间boost::posix_time;
使用名称空间boost::gregorian;
//东部时区为utc-5
typedef boost::日期\时间::本地\调整器美国\东部;
ptime t1(日期(2001年12月31日),小时(19)//纽约时间午夜5小时b/f
ptime t2=美国东部:当地至utc(t1);//t2现在是utc
std::cout这是您使用的程序(免费、开源,将与VS-2013一起运行,确实需要一些)
抱歉,我不熟悉boost库。您的t1
时区是否不知道/不知道日期时间,或者它是否知道时区(即,因为它是您的区域设置,所以已经本地化了纽约)?因为如果它已经是NY本地化的,那么我仍然不理解如何从字符串解析datetime并自动将其设置为NY(因为解析器自动将其设置为我的本地时区而不是NY)。我查阅了boost date_time文档,了解到t1
在这里表示幼稚(不知道时区)的日期时间。然后,一切都好了。。。
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
#include "tz.h"
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
int main()
{
using namespace std;
using namespace date;
vector<string> datetimes{ "2011-01-15 04:01:00",
"2014-06-07 23:17:00",
"2015-11-29 14:55:00" };
zoned_seconds zt("America/New_York");
for (auto const& i : datetimes)
{
stringstream ss1(i);
local_seconds tm;
ss1 >> parse("%F %T", tm);
zt = tm;
stringstream ss2;
ss2 << format("%D %T %Z", zt);
cout << ss2.str() << endl;
}
}
01/15/11 04:01:00 EST
06/07/14 23:17:00 EDT
11/29/15 14:55:00 EST