【发布时间】:2017-10-23 18:51:26
【问题描述】:
我从服务器端(运行 .NET 应用程序)获取 uint64_t 值到我用标准 C++ 编写的应用程序(必须在 Windows 和 Linux 上运行)。
这个数字代表 Windows 文件时间 - 也就是自 1601-01-01 00:00:00 UTC 以来的 100 纳秒间隔。
我需要在我的应用程序中返回时间的字符串表示,精度为纳秒(这是我从服务器获得的值的精度),所以我必须使用 chrono 库。
由于 C++ 的时代是 0001 年 1 月 1 日到 1970 年 1 月 1 日,我首先需要计算从 1970 年到 1601 年的偏移量,然后从我从服务器获得的数字中减去它。为了做到这一点,我首先必须将我从服务器获得的值表示为 chrono::time_point,并以 100 纳秒的间隔计算 1601-01-01 00:00:00 UTC 的纪元,以便它和值我得到的是相同的规模。
在我拥有 addjustedTimeFromServer 之后 - 这是我从服务器获得的值减去(以 chrono::time_point 形式)偏移量,我需要将其转换为 std::time_t 以提取准确的值秒,然后从 chrono::time_point 我需要提取小数秒,这会给我纳秒的精度,我会将它们连接到表示时间的字符串。
这是我的代码。它不能满足我的需要:
using FileTime = duration<int64_t, ratio<1, 10000000>>;
struct std::tm tm;
//create time point for epoch of Windows Filetime (1601-01-01 00:00:00 UTC))
std::istringstream ss("1601-01-01 00:00:00");
ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
std::time_t tt = mktime(&tm);
std::chrono::system_clock::time_point offset =std::chrono::system_clock::from_time_t(tt);
//convert the offset into 100-nanosecond intervals scale
auto offset_ns = std::chrono::time_point_cast<std::chrono::nanoseconds>(offset);
auto offset_100ns = FileTime(offset_ns.time_since_epoch());
//substract the offset from i so now it starts from 1970 like the epoch of C++
auto iDuration = FileTime(static_cast<int64_t>(i));
//auto iDuration_ns = std::chrono::time_point_cast<std::chrono::nanoseconds>(iDuration); //doesn't compile - but that's the idea of what i want to do in this line
std::chrono::system_clock::time_point adjustedTime = iDuration/*iDuration_ns*/ - offset /*-offset_100ns*/; //the commented out parts are what i think is the correct thing to do (scale wise) but they don't compile
//convert the time_point into the string representation i need (extract the regular time, up to seconds, with time_t and the nanosecond part with ns.count())
nanoseconds ns = duration_cast<nanoseconds>(adjustedTime.time_since_epoch());
seconds s = duration_cast<seconds>(ns);
std::time_t t = s.count();
std::size_t fractional_seconds = ns.count() % 10000000;
std::cout << std::ctime(&t) << std::endl;
std::cout << fractional_seconds << std::endl;
代码不起作用,我不知道如何修复它。第一个问题(甚至在所有比例转换问题之前)是 mktime(&tm) 给了我一个不正确的值。由于 tm 表示 C++ 纪元之前的值,因此 mktime(&tm) 返回 -1。我需要以某种方式克服它,因为我必须计算 .NET Filetime 时期(1601-01-01 00:00:00 UTC)的 time_point,以便从我从服务器获得的值中减去它。
我会为这个问题和整个程序提供帮助。
P.S 我只是在此代码中打印,但在最终版本中,我会将这两个部分连接到同一个字符串(ctime(&t) 给出的部分和 fractional_seconds 给出的部分)
【问题讨论】:
标签: c++ date datetime time chrono