I need to calculate the seconds and nanoseconds between the Unix Epoch (00:00:00 January 1st 1970 UTC) and some date in the future the user will select.
Here is what I managed to find so far looking through other Stack Overflow answers:
// seconds and nanoseconds past epoch
auto now = std::chrono::system_clock::now().time_since_epoch();
auto now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now);
auto now_sec = std::chrono::duration_cast<std::chrono::seconds>(now);
// output total ns since epoch
qDebug() << now_ns.count() << "ns";
// output total secs since epoch
qDebug() << now_sec.count() << "secs";
auto nano_secs = now_ns.count() - (now_sec.count() * 1000000000);
// output ns minus whole seconds
qDebug() << "nano_secs = " << nano_secs;
Using this, I am able to get the result I am looking for for the current date and time but that's not what I need. Let's say for demonstration purposes that future date is 00:00:00 July 1st 2020 UTC. How can I go about calculating this?
In C++20 this looks like:
using namespace std::chrono;
nanoseconds now_ns = sys_days{July/1/2020}.time_since_epoch();
auto now_sec = duration_cast<seconds>(now_ns);
now_ns -= now_sec;
std::cout << now_sec << ", " << now_ns << '\n';
Output:
1593561600s, 0ns
Finding a C++20 std::lib that can do this today is going to be difficult. However here is a free, open-source preview of C++20 <chrono>
.
Just add #include "date/date.h"
and using namespace date;
, and it works.
If you don't want to use this 3rd party header, here is the algorithm to convert a {y, m, d}
triple into a count of days since the Unix epoch. Indeed, all sys_days{July/1/2020}
does is call days_from_civil
under the hood and put it into a days-precision chrono::time_point
based on system_clock
. From then on the C++11/14 version of <chrono>
does all of the work.
None of the above computations are dependent on your computer's local timezone setting.