On the various ways of getting the current time and date in Win32
There are a number of functions in Win32that obtain the current date and time.Here’s how they fit together:
The starting point isGetSystemTimeAsFileTime
.This returns the current time in UTC in the form of aFILETIME
structure.This also happens to be the time format used internally by the system,so this value can be retrieved with a minimum of fuss.
You can also callGetSystemTime
which returns the current UTC timein the form of aSYSTEMTIME
structure.To do this, the operating system takes thecurrent FILETIME
and then callsthe moral equivalent ofFileTimeToSystemTime
,whichdoes a boatload of gnarly mathto decompose theFILETIME
into year, month, day, hour, minute, second, and millisecond.
Meanwhile, you can also get the current local time by takingtheFILETIME
returned byGetSystemTimeAsFileTime
,then passing it toFileTimeToLocalFileTime
.
And finally, there’sGetLocalTime
,which does the same thingasGetSystemTime
,but it starts with the local file time.
In equations:
Format | Time zone | Function | Algorithm | |
---|---|---|---|---|
FILETIME | UTC | GetSystemTimeAsFileTime | (Native format) | |
FILETIME | Local | (None) | GetSystemTimeAsFileTime + FileTimeToLocalFileTime | |
SYSTEMTIME | UTC | GetSystemTime | GetSystemTimeAsFileTime | + FileTimeToSystemTime |
SYSTEMTIME | Local | GetLocalTime | GetSystemTimeAsFileTime + FileTimeToLocalFileTime | + FileTimeToSystemTime |
I happen to be a fan of commutative diagrams.(Though since there are no closed loops, there is nothing to commute.)
To complete the commutative diagram,there would be an arrow connecting the bottom two boxes calledSystemTimeToLocalTime
,but there is no such function.
Today’s article was inspired by some code I ran across which did this:
SYSTEMTIME stNow; FILETIME ftNow; GetSystemTime(&stNow); SystemTimeToFileTime(&stNow, &ftNow);
That code unwittingly takes an excursion fromGetSystemTimeAsFileTime
throughFileTimeToSystemTime
toGetSystemTime
,then back throughSystemTimeToFileTime­
toreturn toGetSystemTimeAsFileTime
,just so that it can end up where it started,but with a lot of extra math (and loss of resolution).
Exercise: How would you implement theSystemTimeToLocalTime
function?
0 comments