Question Details

No question body available.

Tags

c++ c++-chrono c++23 stdformat

Answers (3)

Accepted Answer Available
Accepted Answer
January 30, 2026 Score: 4 Rep: 65,749 Quality: High Completeness: 70%

While {:%Q} will work, it is extracting the internal count() from a duration, which is usually unwanted and unnecessary with std::chrono types.

The following will work 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.

January 30, 2026 Score: 5 Rep: 32,573 Quality: Medium Completeness: 70%

It seems from comments that you want to get a floating-point number of years. std::chrono::years is an integer number of years. To get a floating-point value, we need a custom duration:

    using floatyears = duration;
    auto duration = floatyears{tp2 - tp1};
    std::println("duration: {:%Q} year(s)", duration);

That yields

duration: 1.0020739 year(s)

Not exactly one year, because a leap year is about ¾ day longer than an average year (and non-leap years are about ¼ day shorter):

years is equal to 365.2425 days (the average length of a Gregorian year). months is equal to 30.436875 days (exactly 1/12 of years).
-- cppreference

January 30, 2026 Score: 5 Rep: 66,301 Quality: Low Completeness: 60%

You can use the %Q conversion specifier.

std::println("duration: {:%Q} year(s)", duration);

As the comments point out, [31556952]s is the units suffix for std::chrono::years.