language-agnosticdurationleap-second

Which libraries can count seconds correctly and for which dates?


Compute the number of SI seconds between “2021-01-01 12:56:23.423 UTC” and “2001-01-01 00:00:00.000 UTC” as example.


Solution

  • C++20 can do it with the following syntax:

    #include <chrono>
    #include <iostream>
    
    int
    main()
    {
        using namespace std;
        using namespace std::chrono;
    
        auto t0 = sys_days{2001y/1/1};
        auto t1 = sys_days{2021y/1/1} + 12h + 56min + 23s + 423ms;
        auto u0 = clock_cast<utc_clock>(t0);
        auto u1 = clock_cast<utc_clock>(t1);
        cout << u1 - u0 << '\n';  // with leap seconds
        cout << t1 - t0 << '\n';  // without leap seconds
    }
    

    This outputs:

    631198588423ms
    631198583423ms
    

    The first number includes leap seconds, and is 5s greater than the second number which does not.

    This C++20 chrono preview library can do it in C++11/14/17. One just has to #include "date/tz.h", change the y suffix to _y in two places, and add using namespace date;.