[获取时间程序片段]
var
filehandle: Cardinal;
ofstruct: _OFSTRUCT;
fileinformation: _BY_HANDLE_FILE_INFORMATION;
tempfiletime: FILETIME;
systemtime: _SYSTEMTIME;
begin
if OpenDialog1.Execute then
begin
filehandle:=OpenFile(PChar(OpenDialog1.FileName),ofstruct,OF_READ);
if filehandle<>HFILE_ERROR then
begin
if GetFileInformationByHandle(filehandle,fileinformation) then
begin
FileTimeToLocalFileTime(fileinformation.ftCreationTime,tempfiletime);
FileTimeToSystemTime(tempfiletime,systemtime);
showmessage('文件创建时间:'+inttostr(systemtime.wYear)+'年'
+inttostr(systemtime.wMonth)+'月'
+inttostr(systemtime.wDay)+'日, '
+inttostr(systemtime.wHour)+':'
+inttostr(systemtime.wMinute)+':'
+inttostr(systemtime.wSecond));
end
else
showmessage('GetFileInformationByHandle Failed!');//GetLastError shows details
CloseHandle(filehandle);
end
else
showmessage('OpenFile Failed!');//may use GetLastError to show details
end;
end;
[说明]
程序原理:
1.用OpenFile打开文件,获得文件句柄;
2.用GetFileInformationByHandle通过已知的文件句柄获取文件信息,保存到文件信息结构中;
3.用FileTimeToLocalFileTime将格林威治FILETIME转换成当地的FILETIME;
4.用FileTimeToSystemTime将FILETIME类型的时间转换成系统时间,显示该时间;
5.用CloseHandle关闭打开的文件句柄。
注意的是,
GetFileInformationByHandle函数所获得的文件信息中三种时间均是指格林威治标准时间,对应的
系统时间应该加上中国所在的时区(+8)后得到的时间。这里采用的是直接转换的方式,没有转换成
Large_Integer类型再去计算。更简单了。
[设置时间程序片段]
var
SystemTime: _SYSTEMTIME;
CreateTime, LastAccessTime, LastWriteTime: FileTime;
FileHandle: Cardinal;
ofstruct: _OFSTRUCT;
begin
with SystemTime do
try
wYear:=StrToInt(Edit1.Text);
wMonth:=StrToInt(Edit2.Text);
wDay:=StrToInt(Edit3.Text);
wHour:=StrToInt(Edit4.Text);
wMinute:=StrToInt(Edit5.Text);
wSecond:=StrToInt(Edit6.Text);
except
end;
SystemTimeToFileTime(SystemTime,CreateTime);
LocalFileTimeToFileTime(CreateTime,CreateTime);
LastAccessTime:=CreateTime;//见说明
LastWriteTime:=CreateTime; //见说明
if OpenDialog1.Execute then
begin
FileHandle:=OpenFile(PChar(OpenDialog1.FileName),ofstruct,OF_READWRITE);
if FileHandle<>HFILE_ERROR then
try
SetFileTime(FileHandle,
@CreateTime,
@LastAccessTime,
@LastWriteTime);
finally
CloseHandle(FileHandle);
end;
end;
end;
{说明]
这里设置文件的创建时间时,将LastAccessTime和LastWriteTime:=CreateTime也设成
了跟CreateTime一样的时间,当然可以类似另设。注意文件时间有LocalFileTime与FileTime
的区别,程序中有两句话需要注意:
SystemTimeToFileTime(SystemTime,CreateTime); //将系统时间转换为文件时间
LocalFileTimeToFileTime(CreateTime,CreateTime);//将文件时间看成为当地时间并转换为文件时间