我想使用this获取自1970年1月1日以来的ms数。但是,当我尝试编译时,我得到了
"Error: cannot open source file 'sys/time.h'"
我正在使用Visual Studio。
最佳答案
如果使用的是C ++ 11,则可以使用std::chrono
。
#include <chrono>
long long GetUnixTimeChrono()
{
auto timeSinceEpoch = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(timeSinceEpoch).count();
}
否则,您可以这样做:
#include <Windows.h>
long long GetUnixTime()
{
SYSTEMTIME sysUnixEpoch;
sysUnixEpoch.wYear = 1970;
sysUnixEpoch.wMonth = 1;
sysUnixEpoch.wDayOfWeek = 4;
sysUnixEpoch.wDay = 1;
sysUnixEpoch.wHour = 0;
sysUnixEpoch.wMinute = 0;
sysUnixEpoch.wSecond = 0;
sysUnixEpoch.wMilliseconds = 0;
FILETIME unixEpoch;
SystemTimeToFileTime(&sysUnixEpoch, &unixEpoch);
ULARGE_INTEGER unixEpochValue;
unixEpochValue.HighPart = unixEpoch.dwHighDateTime;
unixEpochValue.LowPart = unixEpoch.dwLowDateTime;
FILETIME systemTime;
GetSystemTimeAsFileTime(&systemTime);
ULARGE_INTEGER systemTimeValue;
systemTimeValue.HighPart = systemTime.dwHighDateTime;
systemTimeValue.LowPart = systemTime.dwLowDateTime;
long long diffHundredNanos = systemTimeValue.QuadPart - unixEpochValue.QuadPart;
return diffHundredNanos / 10000;
}