There are a number of functions in Win32 that obtain the current date and time. Here’s how they fit together:
The starting point is
GetSystemTimeAsFileTime
.
This returns the current time in UTC in the form of a
FILETIME
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 call
GetSystemTime
which returns the current UTC time
in the form of a
SYSTEMTIME
structure.
To do this, the operating system takes the
current FILETIME
and then calls
the moral equivalent of
FileTimeToSystemTime
,
which
does a boatload of gnarly math
to decompose the
FILETIME
into year, month, day, hour, minute, second, and millisecond.
Meanwhile, you can also get the current local time by taking
the
FILETIME
returned by
GetSystemTimeAsFileTime
,
then passing it to
FileTimeToLocalFileTime
.
And finally, there’s
GetLocalTime
,
which does the same thing
as
GetSystemTime
,
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 called
SystemTimeToLocalTime
,
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 from
GetSystemTimeAsFileTime
through
FileTimeToSystemTime
to
GetSystemTime
,
then back through
SystemTimeToFileTime­
to
return to
GetSystemTimeAsFileTime
,
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 the
SystemTimeToLocalTime
function?
0 comments