I am trying to get my program to set the system time (Windows 10) using a GPS as a source of truth.
However, despite getting a valid time string from the GPS and converting it to SYSTEMTIME, the clock doesn’t actually update. I confirmed this by setting the clock manually to some wildly incorrect time, hoping my program would then update the clock back to the correct time.
I have the following code, which I’ve cobbled together by looking around online:
// Enable the required privilege
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
if (GetLastError() != ERROR_SUCCESS)
{
// Update the system time
SYSTEMTIME* time = &convertDateTimeToSystemTime(gpsTime);
if (SetSystemTime(time) != NO_ERROR)
{
std::stringstream logStream;
logStream << "Successfully updated system time to: " << timeString;
std::cout << logStream.str() << std::endl;
}
else
{
std::stringstream logStream;
logStream << "Failed to update system time, error code: " << GetLastError();
std::cout << logStream.str() << std::endl;
}
}
else
{
std::stringstream logStream;
logStream << "Failed to adjust token privileges, error code: " << GetLastError();
std::cout << logStream.str() << std::endl;
}
And here’s where I convert my time from the GPS to SYSTEMTIME:
SYSTEMTIME GpsMessageProcessor::convertDateTimeToSystemTime(const Poco::DateTime time)
{
SYSTEMTIME convertedTime;
convertedTime.wYear = time.year();
convertedTime.wMonth = time.month();
convertedTime.wDay = time.day();
convertedTime.wHour = time.hour();
convertedTime.wMinute = time.minute();
convertedTime.wSecond = time.second();
convertedTime.wMilliseconds = time.millisecond();
return convertedTime;
}
The code above outputs:
Failed to update system time, error code : 1314
Which is in the else block of the if (SetSystemTime(time) != NO_ERROR)
condition.
EraticMagician is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1