gpt4 book ai didi

delphi - UTC 支持比较 2 个文件的日期/时间

转载 作者:行者123 更新时间:2023-12-01 23:03:51 25 4
gpt4 key购买 nike

我有一个实用程序可以比较源文件和目标文件的日期/时间。这在大多数情况下有效,但在比较不同时区的文件的日期/时间时会失败。所以我需要一个 UTC 日期时间例程。

环顾四周,Windows API GetFileTime 似乎将支持此功能。我还发现了这个包装程序,但在 Delphi 2010 下编译时,它在 GetFileTime 调用时崩溃。

有什么想法吗?或者是否有人有一段处理 UTC 时区等的代码片段,我可以将 2 个文件名传递给它,告诉我它们是否不同?

function CompareFileTimes(File1, File2 : String) : LongInt;
var
F1, F2 : THandle;
F1_CreateTime,
F1_LastAccess,
F1_LastWrite,
F2_CreateTime,
F2_LastAccess,
F2_LastWrite : PFileTime;
begin
//Initialize all variables
F1 := 0;
F2 := 0;

//Since these are pointers, we have to
//allocate memory for the FileTime structures
GetMem(F1_CreateTime, SizeOf(TFileTime));
GetMem(F1_LastAccess, SizeOf(TFileTime));
GetMem(F1_LastWrite, SizeOf(TFileTime));
GetMem(F2_CreateTime, SizeOf(TFileTime));
GetMem(F2_LastAccess, SizeOf(TFileTime));
GetMem(F2_LastWrite, SizeOf(TFileTime));

//Fill the structures with nulls for now
FillChar(F1_CreateTime, SizeOf(TFileTime), #0);
FillChar(F1_LastAccess, SizeOf(TFileTime), #0);
FillChar(F1_LastWrite, SizeOf(TFileTime), #0);
FillChar(F2_CreateTime, SizeOf(TFileTime), #0);
FillChar(F2_LastAccess, SizeOf(TFileTime), #0);
FillChar(F2_LastWrite, SizeOf(TFileTime), #0);

//Get file handles for the files in question
//Notice that even though we're using CreateFile
//the open disposition for the file is OPEN_EXISTING
F1 := CreateFile(PChar(F1), 0, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
F2 := CreateFile(PChar(F2), 0, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

//Get the file times for the files.
GetFileTime(F1, F1_CreateTime, F1_LastAccess, F1_LastWrite);
GetFileTime(F2, F2_CreateTime, F2_LastAccess, F2_LastWrite);

//Assign the function's result to comparison
//-1, File1 is younger than File2
//0, File1 is the same as File2
//+1 File1 is older than File2
Result := CompareFileTime(F1_CreateTime^, F2_CreateTime^);

//Free the memory allocated to the pointers
FreeMem(F1_CreateTime, SizeOf(TFileTime));
FreeMem(F1_LastAccess, SizeOf(TFileTime));
FreeMem(F1_LastWrite, SizeOf(TFileTime));
FreeMem(F2_CreateTime, SizeOf(TFileTime));
FreeMem(F2_LastAccess, SizeOf(TFileTime));
FreeMem(F2_LastWrite, SizeOf(TFileTime));
end;

任何帮助将不胜感激。

最佳答案

Delphi 2010 已经包含一个简单的包装器,用于在 ioutils.pas 中获取 UTC 时间。下面是一段比较文件的 UTC 创建时间的代码。

uses
IOUtils, DateUtils;

function CompareFileCreationTimeUtc(const aFile1, aFile2: String): integer;
var
lCreationTime1: TDateTime;
lCreationTime2: TDateTime;
begin

lCreationTime1 := TFile.GetCreationTimeUtc(aFile1);
lCreationTime2 := TFile.GetCreationTimeUtc(aFile2);

Result := CompareDateTime(lCreationTime1, lCreationTime2);

end;

关于delphi - UTC 支持比较 2 个文件的日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3490641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com