【问题标题】:Boost, posix time from string issues提升,来自字符串问题的 posix 时间
【发布时间】:2018-05-29 13:42:21
【问题描述】:

我需要使用函数 boost::posix_time::time_from_string(string) 但它不起作用...

举个很简单的例子:

我的代码(main.cpp)

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

using namespace std;

int main() {
    using namespace boost::posix_time;
    cout << "Getting t1" << endl;
    ptime t1 = microsec_clock::universal_time();
    cout << "Getting t1 OK" << endl;

    cout << "Getting t2" << endl;
    ptime t2 = time_from_string(to_iso_string(t1));
    cout << "Getting t2 OK" << endl;
}

输出

Getting t1
Getting t1 OK
Getting t2
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
  what():  bad lexical cast: source type value could not be interpreted as target

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

我的 Cmake

cmake_minimum_required(VERSION 3.10)
project(sandbox)

set(CMAKE_CXX_STANDARD 11)
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.45.0 COMPONENTS date_time)

include_directories(${Boost_INCLUDE_DIRS})
add_executable(sandbox main.cpp)
target_link_libraries(sandbox ${Boost_LIBRARIES})

【问题讨论】:

    标签: c++


    【解决方案1】:

    有两个函数可以从字符串中获取ptimeptime time_from_string(std::string)ptime from_iso_string(std::string)。您想从to_iso_string 返回的字符串中获取ptime,所以应该使用第二个:

    cout << "Getting t2" << endl;
    ptime t2 = from_iso_string(to_iso_string(t1));
    cout << "Getting t2 OK" << endl; // printed
    

    【讨论】:

      【解决方案2】:

      您必须使用from_iso_string 而不是time_from_string

      ptime t2 = from_iso_string(to_iso_string(t1));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多