How do we get a time duration in C++ since a given year?

How do we get a time duration in C++ since a given year? Can we do it with ctime or should we use chrono as well?


Solution 1:

With <chrono> in C++20:

using namespace std::chrono;
using namespace std::chrono_literals;

const auto start = sys_days {2010y / January / 1};
const auto now = system_clock::now();

const auto dur = now - start;

dur is now a std::chrono::duration.

You can use it as is, or you could cast it to a specific unit, e.g.

long ms = duration_cast<milliseconds>(dur).count()

Solution 2:

This can be done quite simply with C++20 and the <chrono> library. Assuming you want to know the duration between now and 2000/01/01, you can do:

using namespace std::literals::chrono_literal;

auto now = std::chrono::system_clock::now();
auto delta = now - std::chrono::sys_days(2000y/1/1);

std::cout << delta;

Note a lot of chrono's feature are not implemented in some major compilers, you might use Howard Hinnant(author of <chrono>)'s Date library.

A demo using the date library: https://godbolt.org/z/ar8P6zY7E, you should be able to simply swap the namespace once the <chrono> library was fully implemented.


Edit, turns out I forgot to use C++20 flag for my demo, with it on: https://godbolt.org/z/5b7bEf6sf