我有一个由刻度数表示的时间戳值。通过创建一个新的System.DateTime对象并将时间戳值传递给构造函数,可以很容易地从c#中获取日期/时间,或者我被告知(它是在c#中创建的)。问题是我只能使用C / C ++。 即使将刻度转换为秒也有点令人困惑。根据cplusplus.com简单乘以宏CLOCKS_PER_SEC - 每秒时钟滴答,应该足够了。这导致乘以1000.但是,根据Microsoft网站,转换因子为秒应为1e7。要转换的样本值是634400640022968750,这表明第二个版本更接近现实。
我不会花时间描述我失败的尝试,因为他们让我无处可去。 任何帮助都将深表感谢。
答案 0 :(得分:1)
假设你在windows上,问题是c#DateTime从0001年1月1日开始,c ++ FILETIME从1601年1月1日开始,所以要获得一个带有C#值的SYSTEMTIME,你需要这样的东西......
ULARGE_INTEGER uliTime;
uliTime.QuadPart = 634400640022968750; // Your sample value
SYSTEMTIME stSytemTime;
memset(&stSytemTime,0,sizeof(SYSTEMTIME));
FILETIME stFileTime;
memset(&stFileTime,0,sizeof(FILETIME));
// Fill FILETIME with your value
stFileTime.dwLowDateTime = uliTime.LowPart;
stFileTime.dwHighDateTime = uliTime.HighPart;
// Convert FILETIME so SYSTEMTIME
FileTimeToSystemTime(&stFileTime, &stSytemTime);
stSytemTime.wYear -= 1600; // Remove the "start" diference
将SYSTEMTIME转换为time_t
void ConvertSystemTimeToTimeT(const SYSTEMTIME &stSystemTime, time_t &stTimeT)
{
// time_t min value is 1 January 1970
LARGE_INTEGER liJanuary1970 = {0};
liJanuary1970.QuadPart = 116444736000000000;
FILETIME stFileTime = {0};
SystemTimeToFileTime(&stSystemTime, &stFileTime);
ULARGE_INTEGER ullConverter;
ullConverter.LowPart = stFileTime.dwLowDateTime;
ullConverter.HighPart = stFileTime.dwHighDateTime;
// time_t resolution is 1 second, FILETIME is 100 nanoseconds, so convert to seconds and remove the 1970 value
stTimeT = (time_t)(ullConverter.QuadPart - liJanuary1970.QuadPart) / 10000000;
}
答案 1 :(得分:0)
如果您想为代码计时,我建议您使用QueryPerformance library(QueryPerformanceFrequency
和QueryPerformanceCounter
函数),如果您的硬件支持它。
如果您只想要一个纪元的秒数时间戳,请使用"time.h"
库:How to get current time and date in C++?