Skip to main content
5 of 5
added 95 characters in body
Drew Dormann
  • 65.8k
  • 14
  • 133
  • 202

I was expecting a duration of exactly 1 year without fractional seconds,

While {:%Q} could work, it is extracting the internal count() from a duration, which is dangerous and usually unnecessary with std::chrono types. If a code change alters the duration's period, you will start getting incorrect values.

The following will give you a year count regardless of the internal representation of your duration.

The code is also smaller and arguably clearer.

    auto duration = tp2 - tp1;
    std::println("duration: {} year(s)", duration / years{1});

The lesson: dividing two durations gives you a correct count without needing to know (or duration_cast) either duration's representation.

See it work.

Drew Dormann
  • 65.8k
  • 14
  • 133
  • 202