Search code examples
c++parsingc++-chrono

What is wrong with parsing this time string for 'std::chrono'?


I simple want to parse a time-string to a chrono::system_clock::time_point using:

#include <iosfwd>
#include "date/date.h"

std::stringstream ssTime;
ssTime << "17:34:05";
std::chrono::system_clock::time_point tp_time;
ssTime >> date::parse("%H:%M:%S", tp_time);

I expected to get the time_point of the specified time after EPOCH, but instead I get 0 (i.e. EPOCH).

Note, that I'm using the date library of Howard Hinnant .


Solution

  • The design of the parse function is that if you don't parse enough information for the type being parsed, the failbit is set on the stream. parse considers the {h, m, s} information insufficient for uniquely determining an instant in time (a system_clock::time_point), so this parse fails.

    You can make this work by parsing into a seconds duration instead:

    #include "date/date.h"
    #include <sstream>
    
    int
    main()
    {
        std::stringstream ssTime;
        ssTime << "17:34:05";
        std::chrono::seconds tp_time;
        ssTime >> date::parse("%H:%M:%S", tp_time);
    }
    

    tp_time will have the value of 63245s in this example.