如何获取文件夹的创建日期并转换为TDateTime类型?
获取文件夹创建日期并转换为TDateTime的方法
方法一:使用Windows API(兼容所有Delphi版本)
通过Windows API的FindFirstFile获取文件夹的创建时间戳,再逐步转换为TDateTime类型,适用于所有Delphi版本:
function GetFolderCreationDateTime(const AFolderPath: string): TDateTime; var FindHandle: THandle; FindData: WIN32_FIND_DATA; SystemTime: TSystemTime; begin // 确保路径以反斜杠结尾,避免匹配到同名文件 FindHandle := FindFirstFile(PChar(IncludeTrailingPathDelimiter(AFolderPath)), FindData); try if FindHandle <> INVALID_HANDLE_VALUE then begin // 将UTC文件时间转换为本地时间 FileTimeToLocalFileTime(FindData.ftCreationTime, FindData.ftCreationTime); // 转换为系统时间结构 FileTimeToSystemTime(FindData.ftCreationTime, SystemTime); // 转换为TDateTime类型 Result := SystemTimeToDateTime(SystemTime); end else raise Exception.Create('无法访问文件夹:' + SysErrorMessage(GetLastError)); finally FindClose(FindHandle); end; end;
调用示例:
var FolderDT: TDateTime; begin FolderDT := GetFolderCreationDateTime('C:\YourTargetFolder'); end;
方法二:使用Delphi RTL的TFile类(Delphi XE2及以上版本)
Delphi XE2及更高版本引入了IOUtils单元,其中TFile.GetCreationTime方法可以直接返回文件夹的创建时间,无需手动处理API调用:
uses IOUtils; var FolderDT: TDateTime; begin FolderDT := TFile.GetCreationTime('C:\YourTargetFolder'); end;
注意事项
- 两种方法在文件夹路径不存在时都会抛出异常,建议使用时添加
try-except块处理错误 - 方法一中的
IncludeTrailingPathDelimiter是必要的,确保FindFirstFile识别目标为文件夹而非同名文件
内容的提问来源于stack exchange,提问作者WayOfTheWright
相关产品推荐
相关产品推荐

