C++ Converting a Datetime String to Epoch Cleanly

后端 未结 3 614
余生分开走
余生分开走 2020-12-19 04:07

Is there a C/C++/STL/Boost clean method to convert a date time string to epoch time (in seconds)?

yyyy:mm:dd hh:mm:ss
3条回答
  •  长情又很酷
    2020-12-19 04:33

    See: Date/time conversion: string representation to time_t

    And: [Boost-users] [date_time] So how come there isn't a to_time_t helper func?

    So, apparently something like this should work:

    #include 
    using namespace boost::posix_time;
    
    std::string ts("2002-01-20 23:59:59");
    ptime t(time_from_string(ts));
    ptime start(gregorian::date(1970,1,1)); 
    time_duration dur = t - start; 
    time_t epoch = dur.total_seconds();    
    

    But I don't think it's much cleaner than Rob's suggestion: use sscanf to parse the data into a struct tm and then call mktime.

提交回复
热议问题