更新
我稍微修改了下面的代码以在SYSTEMTIME 和date::sys_time<std::chrono::milliseconds> 之间转换,而不是date::sys_time<std::chrono::nanoseconds>。
基本原理: 这样to_SYSTEMTIME 中就没有隐含的精度损失。 to_SYSTEMTIME 的客户端可以以他们想要的任何方式显式截断精度(floor、round、ceil 等)。并且未能截断精度(如果需要)不会是静默运行时错误。
客户端代码(main)不受此更改的影响。
您可以为此使用Howard Hinnant's free, open-source, header-only date/time library:
#include "date/date.h"
#include <iostream>
using WORD = int;
struct SYSTEMTIME {
/** year */
WORD year;
/** month */
WORD month;
/** day of week */
WORD dayOfWeek;
/** day */
WORD day;
/** hour */
WORD hour;
/** minute */
WORD minute;
/** second */
WORD second;
/** milliseconds */
WORD milliseconds;
};
date::sys_time<std::chrono::milliseconds>
to_sys_time(SYSTEMTIME const& t)
{
using namespace std::chrono;
using namespace date;
return sys_days{year{t.year}/t.month/t.day} + hours{t.hour} +
minutes{t.minute} + seconds{t.second} + milliseconds{t.milliseconds};
}
int
main()
{
using namespace std::chrono;
using namespace date;
SYSTEMTIME st{2017, 12, 2, 19, 14, 44, 0, 0};
auto t = to_sys_time(st) + 397000ns;
std::cout << floor<microseconds>(t) << '\n';
}
输出:
2017-12-19 14:44:00.000397
这通过收集SYSTEMTIME 中的不同部分,将SYSTEMTIME 转换为std::chrono::time_point<system_clock, milliseconds>(具有名为date::sys_time<milliseconds> 的类型别名)。然后它简单地将nanoseconds 添加到time_point,将其截断为microseconds 的所需精度,然后将其流出。
如果有帮助,您可以使用相同的库进行相反的转换:
SYSTEMTIME
to_SYSTEMTIME(date::sys_time<std::chrono::milliseconds> const& t)
{
using namespace std::chrono;
using namespace date;
auto sd = floor<days>(t);
year_month_day ymd = sd;
auto tod = make_time(t - sd);
SYSTEMTIME x;
x.year = int{ymd.year()};
x.month = unsigned{ymd.month()};
x.dayOfWeek = weekday{sd}.c_encoding();
x.day = unsigned{ymd.day()};
x.hour = tod.hours().count();
x.minute = tod.minutes().count();
x.second = tod.seconds().count();
x.milliseconds = tod.subseconds().count();
return x;
}