Skip to main content
2 of 2
deleted 12 characters in body
r5g5
  • 21
  • 3

duration_cast returns a duration object rather than a raw numeric value. The number shown in brackets represents the number of seconds in one year. The quick solution for your case is to call the count() member function of the duration class. For reference: https://en.cppreference.com/w/cpp/chrono/duration/count.html

duration: 1[31556952]s year(s)
// Source - https://stackoverflow.com/q/79879480
// Posted by Angle.Bracket, modified by community. See post 'Timeline' for change history
// Retrieved 2026-01-31, License - CC BY-SA 4.0

#include <print>
#include <chrono>
#include <string>
int main() {
    using namespace std::chrono;
    system_clock::time_point tp1;
    system_clock::time_point tp2;

    std::string y1 = "01.01.2024";
    std::string y2 = "01.01.2025";
    
    std::istringstream is1{ y1.data() };
    is1 >> parse("%d.%m.%Y", tp1);
    std::istringstream is2{ y2.data() };
    is2 >> parse("%d.%m.%Y", tp2);

    std::println("{}", tp1); // 2024-01-01 00:00:00.000000000 
    std::println("{}", tp2); // 2025-01-01 00:00:00.000000000 

    auto duration = duration_cast<years>(tp2 - tp1).count(); // NOTE: Modified here
    std::println("duration: {} year(s)", duration); // duration: 1 year(s) 

    return 0;
}
r5g5
  • 21
  • 3