This is very easy to do using Howard Hinnant's time/date library.
#include "date/date.h"
#include <iostream>
date::sys_time<std::chrono::seconds>
to_time_point(double d)
{
using namespace date;
using namespace std::chrono;
using ddays = duration<double, days::period>;
return round<seconds>(ddays{d} + sys_days{1582_y/10/15});
}
int
main()
{
using namespace date;
std::cout << to_time_point(159562.572297) << '\n';
}
Output:
2019-08-27 13:44:06
You didn't mention what precision you wanted, but from your example output, I presumed seconds. You can choose any chrono-precision you desire. This program simply converts your double
into a double
-based chrono-duration with a period of days
, and then adds it to the epoch. The result is a chrono::system_clock::time_point
with a precision of your choosing. Though I recommend you don't use nanoseconds
. nanoseconds
precision is 3 orders of magnitude finer than the double
will deliver at this range, and the range of sys_time<nanoseconds>
is [1677-09-21 00:12:43.145224192, 2262-04-11 23:47:16.854775807]. Whereas the range of sys_time<microseconds>
is +/-292 thousand years (plenty).
You can use this same library to format this time_point
in whatever style you want. For example:
std::cout << format("%d:%m:%YT%T", to_time_point(159562.572297)) << '\n';
Output:
27:08:2019T13:44:06
Use of this library will migrate very nicely to C++20 if you ever choose to use that newer standard once it becomes available.