使用Howard Hinnant的时间/日期库,这很容易做到。
#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';
}
Run Code Online (Sandbox Code Playgroud)
输出:
2019-08-27 13:44:06
Run Code Online (Sandbox Code Playgroud)
您没有提到想要的精度,但是从您的示例输出中,我认为是几秒钟。您可以选择所需的任何时间精度。该程序只是将您的时间转换double为double基于时间的时间段,时间段为days,然后将其添加到纪元。结果是chrono::system_clock::time_point您所选择的精度。虽然我建议您不要使用nanoseconds。 nanoseconds精度比double此范围内的精度高3个数量级,范围sys_time<nanoseconds>为[1677-09-21 00:12:43.145224192,2262-04-11 23:47:16.854775807]。而范围sys_time<microseconds>是+/- 29.2万年(很多)。
您可以使用相同的库将其格式化time_point为所需的任何样式。例如:
std::cout << format("%d:%m:%YT%T", to_time_point(159562.572297)) << '\n';
Run Code Online (Sandbox Code Playgroud)
输出:
27:08:2019T13:44:06
Run Code Online (Sandbox Code Playgroud)
如果您选择使用较新的标准,则使用此库将非常好地迁移到C ++ 20。