lundi 16 novembre 2020

C++ Directly Convert std::string to std::chrono::duration

I am trying to convert "%H:%M:%S". e.g, "00:15:00" in string format to chrono::duration in C++11. I came up with the following where I calculate two timepoints with respect to the system_clock or steady_clock: (1) "00:15:00" and (2) "00:00:00". I then subtract them from each other to get the duration.

std::tm tm0 = {}, tm1{};
std::stringstream ss0("00:00:00"), ss1("00:15:00");
ss0 >> std::get_time(&tm0, "%H:%M:%S");
ss1 >> std::get_time(&tm1, "%H:%M:%S");
auto t0 = std::chrono::system_clock::from_time_t(std::mktime(&tm0));
auto t1 = std::chrono::system_clock::from_time_t(std::mktime(&tm1));
auto d = t1-t0;
std::cout << std::chrono::duration_cast<std::chrono::seconds>(d).count();

It does the conversion but I was wondering if there is an elegant way or direct way of achieving this.

Aucun commentaire:

Enregistrer un commentaire