如何将TDateTime转换为FILETIME?

时间:2017-05-10 09:16:04

标签: delphi delphi-xe5

标题说明了一切。互联网上有很多例子如何将FILETIME转换为TDateTime但不是相反。

3 个答案:

答案 0 :(得分:3)

  1. DateTimeToSystemTime致电System.SysUtils
  2. SystemTimeToFileTime致电Winapi.Windows
  3. 如果您的原始日期时间值是当地时间,那么您需要在调用DateTimeToSystemTime之前将其转换为UTC。

答案 1 :(得分:1)

您可以在ConvertDateTimeToFileTime中查看System.IOUtils的实现。 它是TDirectory记录的私有成员。 但是您可以将其用作参考,以便在一个功能中实现所需的所有功能。

答案 2 :(得分:0)

function FileTimeToDateTime(AFileTime: FILETIME): TDateTime;
var
    li: ULARGE_INTEGER;
    systemTime: TSystemTime;
    localTime: TSystemTime;
const
    OA_ZERO_TICKS = UInt64(94353120000000000);
    TICKS_PER_DAY = UInt64(864000000000);
begin
    // Convert a FILETIME (which is UTC by definition), into a UTC TDateTime.

    // Copy FILETIME into LARGE_INTEGER to allow UInt64 access without alignment faults.
    li.LowPart := AFileTime.dwLowDateTime;
    li.HighPart := AFileTime.dwHighDateTime;
    Result := (Real(li.QuadPart) - OA_ZERO_TICKS) / TICKS_PER_DAY;
end;

function DateTimeToFileTime(ADateTimeUTC: TDateTime): FILETIME;
var
    li: ULARGE_INTEGER;
    systemTime: TSystemTime;
    localTime: TSystemTime;
const
    OA_ZERO_TICKS = UInt64(94353120000000000);
    TICKS_PER_DAY = UInt64(864000000000);
begin
    // Convert a UTC TDateTime into a FILETIME (which is UTC by definition).

    li.QuadPart := Round(ADateTimeUtc*TICKS_PER_DAY + OA_ZERO_TICKS);
    Result.dwLowDateTime := li.LowPart;
    Result.dwHighDateTime := li.HighPart;
end;

通过避免SYSTEMTIME,我们避免了losing precision in milliseconds.

根据定义,SYSTEMTIME的dwMilliseconds限制为1毫秒。

| FILETIME                       | SYSTEMTIME              |
|--------------------------------|-------------------------|
| 100ns resolution               | 1,000,000 ns resolution |
| GetSystemTimeAsFileTime        | GetSystemTime           |
| GetSystemTimePreciseAsFileTime | n/a                     |
|                   -- FileTimeToSystemTime -->            |
|                  <-- SystemTimeToFileTime --             |

您应避免使用SYSTEMTIMESYSTEMTIME的目的是为您将日期/时间解码为其组成部分:

  • 年,月,日,时,分,秒,毫秒

奖金阅读