我需要使用ISO扩展格式读取时间,并将其转换为UTC时间,就像Javascript的Date
个对象一样:
新日期(" 2014-12-19T15:53:14.533 + 01:00")
2014-12-19T14:53:14.533Z
在提升中,没有boost::posix_time::from_iso_extended_string
且boost::posix_time::from_iso_string
无法解析时区。我尝试使用boost::local_time::local_date_time
,但似乎它也不起作用:
std::stringstream ss("2014-12-19T15:53:14.533+01:00");
boost::local_time::local_time_input_facet*
ifc= new boost::local_time::local_time_input_facet();
ifc->set_iso_extended_format();
ss.imbue(std::locale(ss.getloc(), ifc));
boost::local_time::local_date_time
zonetime(boost::local_time::not_a_date_time);
if( ss >> zonetime ) {
time = zonetime.utc_time();
}
任何帮助或建议?
答案 0 :(得分:2)
根本不解析时区:
<强> Live On Coliru 强>
#include <iostream>
#include <sstream>
#include <boost/date_time.hpp>
int main()
{
boost::posix_time::ptime time;
try
{
std::stringstream ss("2014-12-19T15:53:14.533+01:00");
boost::local_time::local_time_input_facet* ifc= new boost::local_time::local_time_input_facet();
ifc->set_iso_extended_format();
ss.imbue(std::locale(ss.getloc(), ifc));
boost::local_time::local_date_time zonetime(boost::local_time::not_a_date_time);
if( ss >> zonetime ) {
time = zonetime.utc_time();
}
std::string remains;
if (std::getline(ss, remains))
std::cout << "Remaining: '" << remains << "'\n";
}
catch( std::exception const& e )
{
std::cout << "ERROR:" << e.what() <<std::endl;
}
std::cout << "UTC time: " << time;
return 0;
}
打印:
Remaining: '+01:00'
UTC time: 2014-Dec-19 15:53:14.533000
此时,local_date_time对象只能使用Posix时区字符串进行流式传输。有关Posix时区字符串的完整说明,请参见posix_time_zone类的文档。
因此,您需要单独解析时区或使用POSIX时区。是的,我认为这是非常令人困惑和缺陷。实际上,您不能在本地时间使用扩展iso格式。
您可以使用%ZP
来代替:
<强> Live On Coliru 强>
#include <iostream>
#include <sstream>
#include <boost/date_time.hpp>
int main()
{
boost::posix_time::ptime time;
try
{
std::stringstream ss("2014-12-19T15:53:14.533-07:00");
boost::local_time::local_time_input_facet* ifc= new boost::local_time::local_time_input_facet("%Y-%m-%d %H:%M:%S%F %ZP");
//ifc->set_iso_extended_format();
ss.imbue(std::locale(ss.getloc(), ifc));
using namespace boost::local_time;
local_date_time ldt(not_a_date_time);
if(ss >> ldt) {
time = ldt.utc_time();
std::string remains;
if (std::getline(ss, remains))
std::cout << "Remaining: '" << remains << "'\n";
}
}
catch( std::exception const& e )
{
std::cout << "ERROR:" << e.what() <<std::endl;
}
std::cout << "UTC time: " << time;
return 0;
}
打印
UTC time: 2014-Dec-19 22:53:14.533000