Home > OS >  How check what boost::datetime correct?
How check what boost::datetime correct?

Time:07-29

How i can check what input string incorrect and throw exception? Now it string just accepting to constructor and converting to something wrong but exception not throw

#include <boost/date_time.hpp>

namespace bt = boost::posix_time;
using namespace boost;
using namespace gregorian;
using namespace boost::posix_time;
    
constexpr const char format[] = "%Y-%m-%d %H:%M:%S";

bt::ptime from_string_dtime(const std::string& s)
{
    bt::ptime pt;
    std::istringstream is(s);
    is.imbue(std::locale(std::locale::classic(), new bt::time_input_facet(format)));
    is >> pt;
    return pt;
}

class dt_wrap
{
public:
    dt_wrap() = default;
    dt_wrap(const std::string& dtime);
    ~dt_wrap() = default;
    
private:
    bt::ptime d_time;
};

dt_wrap::dt_wrap(const std::string& dtime)
:   d_time(from_string_dtime(dtime))
{}

int main()
{
    dt_wrap dt("2006-04-25 24:25:25");
    dt_wrap dt("incorrect_string"); // need throw exception incorrect format
}

CodePudding user response:

Hope it help someone. Need set the streams exception flags.

bt::ptime from_string_dtime(const std::string& s)
{
    bt::ptime pt;
    std::istringstream is(s);
    is.exceptions(std::ifstream::failbit | std::ifstream::badbit); // Set exception flags
    is.imbue(std::locale(std::locale::classic(), new bt::time_input_facet(format)));
    is >> pt;
    return pt;
}
  • Related