主要問題似乎是獲取文件的上次修改時間。我使用下面的代碼:
function LastWriteTime(const FileName: string): TFileTime;
var
AttributeData: TWin32FileAttributeData;
begin
if not GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @AttributeData) then
RaiseLastOSError;
Result := AttributeData.ftLastWriteTime;
end;
function UTCFileTimeToSystemTime(const FileTime: TFileTime): TSystemTime;
//returns equivalent time in current locality, taking account of daylight saving
var
LocalFileTime: Windows.TFileTime;
begin
Windows.FileTimeToLocalFileTime(FileTime, LocalFileTime);
Windows.FileTimeToSystemTime(LocalFileTime, Result);
end;
function UTCFileTimeToDateTime(const FileTime: TFileTime): TDateTime;
begin
Result := SystemTimeToDateTime(UTCFileTimeToSystemTime(FileTime));
end;
你叫LastWriteTime
獲得文件時間格式的最後修改時間。然後撥打UTCFileTimeToDateTime
轉換爲TDateTime
,說明機器當前的當地時區。然後,您可以將該值與Now
進行比較。
至於格式,你已經知道如何做到這一點。你的基本方法將起作用,你只需要充實細節。
在評論你說
FormatDateTime('dd hh:nn:ss', 2.9);
顯示時,你會期望一個2
當天1
。問題是這個函數格式化日期而不是時間間隔。值2.9
不被視爲已用時間,而是被視爲絕對日期/時間,在德爾福時代後的2.9
天。我將使用Trunc
和Frac
分別獲取天數和部分天數,並從那裏開始工作。
Days := Trunc(TimeDiff);
Time := Frac(TimeDiff);
下面的代碼,直接從我的代碼庫中提取,可能會給你一些指針。請注意,它的輸入是以秒爲單位的,但它應該將您設置在正確的路徑上。
function CorrectPlural(const s: string; Count: Integer): string;
begin
Result := IntToStr(Count) + ' ' + s;
if Count<>1 then begin
Result := Result + 's';
end;
end;
function HumanReadableTime(Time: Double): string;
//Time is in seconds
const
SecondsPerMinute = 60;
SecondsPerHour = 60*SecondsPerMinute;
SecondsPerDay = 24*SecondsPerHour;
SecondsPerWeek = 7*SecondsPerDay;
SecondsPerYear = 365*SecondsPerDay;
var
Years, Weeks, Days, Hours, Minutes, Seconds: Int64;
begin
Try
Years := Trunc(Time/SecondsPerYear);
Time := Time - Years*SecondsPerYear;
Weeks := Trunc(Time/SecondsPerWeek);
Time := Time - Weeks*SecondsPerWeek;
Days := Trunc(Time/SecondsPerDay);
Time := Time - Days*SecondsPerDay;
Hours := Trunc(Time/SecondsPerHour);
Time := Time - Hours*SecondsPerHour;
Minutes := Trunc(Time/SecondsPerMinute);
Time := Time - Minutes*SecondsPerMinute;
Seconds := Trunc(Time);
if Years>5000 then begin
Result := IntToStr(Round(Years/1000))+' millennia';
end else if Years>500 then begin
Result := IntToStr(Round(Years/100))+' centuries';
end else if Years>0 then begin
Result := CorrectPlural('year', Years) + ' ' + CorrectPlural('week', Weeks);
end else if Weeks>0 then begin
Result := CorrectPlural('week', Weeks) + ' ' + CorrectPlural('day', Days);
end else if Days>0 then begin
Result := CorrectPlural('day', Days) + ' ' + CorrectPlural('hour', Hours);
end else if Hours>0 then begin
Result := CorrectPlural('hour', Hours) + ' ' + CorrectPlural('minute', Minutes);
end else if Minutes>0 then begin
Result := CorrectPlural('minute', Minutes);
end else begin
Result := CorrectPlural('second', Seconds);
end;
Except
Result := 'an eternity';
End;
end;
+1尤其適用於考慮夏令時。 – 2012-05-12 15:09:06
謝謝!但是還是有些問題......'FormatDateTime('dd hh:nn:ss',TimeDiff);'其中TimeDiff ='2.9487917361'(距離文件上次修改和現在差不多3天)給了我01 22:46:15 ' – TheDude
我希望我的最新更新有所幫助。 –