Convert Windows Filetime to second in Unix/Linux

2019-01-05 03:51发布

I have a trace file that each transaction time represented in Windows filetime format. These time numbers are something like this:

  • 128166372003061629
  • 128166372016382155
  • 128166372026382245

Would you please let me know if there are any C/C++ library in Unix/Linux to extract actual time (specially second) from these numbers ? May I write my own extraction function ?

标签: c++ c time
9条回答
贼婆χ
2楼-- · 2019-01-05 04:19

(I discovered I can't enter readable code in a comment, so...)

Note that Windows can represent times outside the range of POSIX epoch times, and thus a conversion routine should return an "out-of-range" indication as appropriate. The simplest method is:

   ... (as above)
   long long secs;
   time_t t;

   secs = (windowsTicks / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
   t = (time_t) secs;
   if (secs != (long long) t)    // checks for truncation/overflow/underflow
      return (time_t) -1;   // value not representable as a POSIX time
   return t;
查看更多
叛逆
3楼-- · 2019-01-05 04:20

Here's essentially the same solution except this one encodes negative numbers from Ldap properly and lops off the last 7 digits before conversion.

    public static int LdapValueAsUnixTimestamp(SearchResult searchResult, string fieldName)
    {
        var strValue = LdapValue(searchResult, fieldName);
        if (strValue == "0") return 0;
        if (strValue == "9223372036854775807") return -1;

        return (int)(long.Parse(strValue.Substring(0, strValue.Length - 7)) - 11644473600);
    }
查看更多
唯我独甜
4楼-- · 2019-01-05 04:21

The solution that divides and adds will not work correctly with daylight savings.

Here is a snippet that works, but it is for windows.

time_t FileTime_to_POSIX(FILETIME ft)
{
    FILETIME localFileTime;
    FileTimeToLocalFileTime(&ft,&localFileTime);
    SYSTEMTIME sysTime;
    FileTimeToSystemTime(&localFileTime,&sysTime);
    struct tm tmtime = {0};
    tmtime.tm_year = sysTime.wYear - 1900;
    tmtime.tm_mon = sysTime.wMonth - 1;
    tmtime.tm_mday = sysTime.wDay;
    tmtime.tm_hour = sysTime.wHour;
    tmtime.tm_min = sysTime.wMinute;
    tmtime.tm_sec = sysTime.wSecond;
    tmtime.tm_wday = 0;
    tmtime.tm_yday = 0;
    tmtime.tm_isdst = -1;
    time_t ret = mktime(&tmtime);
    return ret;
}
查看更多
登录 后发表回答