简体   繁体   中英

How to correctly convert Unix time to FILETIME used by Win32

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM