I am trying to get the number of ms since jan 01 1970 using this. However when I try to compile I get
"Error: cannot open source file 'sys/time.h'"
I am using Visual Studio.
The sys/time.h
header is a POSIX header and as such is not typically found on a Windows machine, and certainly not in a Windows SDK. For Visual Studio you need to include time.h
rather than sys/time.h
, as described in the documentation.
But the functions in the Visual Studio time.h
don't give you millisecond precision. There is not gettimeofday()
. The best you can do is Unix time in seconds. Now, millisecond precision Unix time on Windows was the subject of this question: How can i get UTCTime in millisecond since January 1, 1970 in c language. However, the accepted answer is dire and really should be deleted.
After a bit more diffing, I think you will find what you need here: Convert Windows Filetime to second in Unix/Linux. The workflow goes like this:
GetSystemTime()
to get the system time.SystemTimeToFileTime
to convert to file time.I think this is what you need, but bear in mind I am not remotely fluent in C++:
#include <windows.h>
long long GetUnixTime()
{
const long long WINDOWS_TICK = 10000000LL;
const long long SEC_TO_UNIX_EPOCH = 11644473600LL;
SYSTEMTIME st;
GetSystemTime(&st);
FILETIME ft;
if (!SystemTimeToFileTime(&st, &ft))
return -1;
ULARGE_INTEGER uli;
uli.LowPart = ft.dwLowDateTime;
uli.HighPart = ft.dwHighDateTime;
return uli.QuadPart / WINDOWS_TICK - SEC_TO_UNIX_EPOCH;
}
If you are using C++ 11, you can use 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();
}
Otherwise, you can do this:
#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;
}