How to correctly convert Unix time to FILETIME used by Win32

765 Views Asked by At

Microsoft offers the following function in its support article :

   // NOTE: this function is INCORRECT!
   void UnixTimeToFileTime(time_t t, LPFILETIME pft)
   {
     // Note that LONGLONG is a 64-bit value
     LONGLONG ll;
     ll = Int32x32To64(t, 10000000) + 116444736000000000;
     pft->dwLowDateTime = (DWORD)ll;
     pft->dwHighDateTime = ll >> 32;
   }

However, if the Unix time "t" refers to the dates after the year 2038, this function produces an incorrect result. How to make it work properly after the year 2038?

1

There are 1 best solutions below

0
On

The problem is the use of the Int32x32To64 function, because it truncates its arguments to 32-bits each. If the unix time exceeds 32 bits (as it happens for the dates after the year 2038), it produces an incorrect result. To correct the problem, use 64-bit multiplication instead of the Int32x32To64 function:

   void UnixTimeToFileTime(time_t t, LPFILETIME pft)
   {
     // Note that LONGLONG is a 64-bit value
     LONGLONG ll;
     ll = t * 10000000I64 + 116444736000000000I64;
     pft->dwLowDateTime = (DWORD)ll;
     pft->dwHighDateTime = ll >> 32;
   }

Hope this saves time someone.