BaptisteM
BaptisteM

Reputation: 155

Boost, posix time from string issues

I need to use the function boost::posix_time::time_from_string(string) but it doesn't work ...

With a very simple exemple :

My code (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;
}

Output

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)

My 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})

Upvotes: 0

Views: 1663

Answers (2)

Jorge
Jorge

Reputation: 137

You have to use from_iso_string instead of time_from_string

ptime t2 = from_iso_string(to_iso_string(t1));

Upvotes: 1

rafix07
rafix07

Reputation: 20938

There are two functions to get ptime from string, ptime time_from_string(std::string) and ptime from_iso_string(std::string). You want to get ptime from string returned by to_iso_string so should use the second:

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

Upvotes: 1

Related Questions