gpt4 book ai didi

c++ - boost::local_time 未读取正确的 iso_extended_format

转载 作者:行者123 更新时间:2023-12-02 18:25:40 25 4
gpt4 key购买 nike

我需要读取 ISO 扩展格式的时间,并将其转换为 UTC 时间,就像 Javascript 的 Date 对象所做的那样:

new Date("2014-12-19T15:53:14.533+01:00")

2014-12-19T14:53:14.533Z

在 boost 中,没有 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();
}

有什么帮助或建议吗?

Live on coliru

最佳答案

时区根本没有被解析:

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

documentation says :

At this time, local_date_time objects can only be streamed in with a Posix Time Zone string. A complete description of a Posix Time Zone string can be found in the documentation for the posix_time_zone class.

因此,您需要单独解析时区或使用 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

关于c++ - boost::local_time 未读取正确的 iso_extended_format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28193719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com