Parsing datetime issue using chrono

102 views Asked by At

I have this function that returns a time_point(system_clock).

using time_point_t = std::chrono::sys_time<std::chrono::microseconds>;

time_point_t decrypt(std::string s) {
  time_point_t tp;
  std::istringstream in(s);
  in >> std::chrono::parse("%Y%m%d-%T", tp);
  return tp;
}

When I try to parse this string "20240304-13:00:00:00.002", and display the output, I got 2024-03-04 13:00:00:00.001999

What's wrong, and how to fix this ?

Does std::chrono::ceil(time_point) fix the issue ?

https://godbolt.org/z/Mq68s4f3s

2

There are 2 answers

0
Howard Hinnant On BEST ANSWER

round should fix this issue:

in >> parse("%Y%m%d-%T", tp);
using namespace std::chrono;
return round<milliseconds>(tp);
0
Ted Lyngmo On

At least in gcc, you'll get a better result if you parse the microseconds separately:

auto decrypt(std::string s) {
    std::chrono::sys_seconds tp; // note seconds only
    std::string micro;
    std::istringstream in(s);
    in >> std::chrono::parse("%Y%m%d-%T.", tp) >> std::setw(6) >> micro;
    micro.resize(6, '0');
    return tp + std::chrono::microseconds(std::stoi(micro));
}

Note that this doesn't do any error checking if the micro string contains illegal characters etc.

Demo