我正在建立一個倒計時到某個日期/時間的東西。我有它的工作 - 至少小時,分鐘和秒工作正常。我的問題是當我嘗試實施天時,它沒有給出正確的結果。我知道DateUtils的單元,但那裏有很多東西,我不知道該怎麼做,特別是因爲我數學很糟糕。日期/時間操縱友好的倒計時字符串
我有一個間隔爲100的計時器。然後我有一個全球的fDestDT
爲目標日期/時間倒計時的基礎。在計時器中,我有一個名爲DT
的本地TDateTime。然後,我打破它分爲多個字符串,並把他們重新走到一起進1「友好」串...
procedure TForm1.TmrTimer(Sender: TObject);
var
DT: TDateTime;
D, H, N, S: String;
Str: String;
begin
DT:= fDestDT - Now; //fDest = destination date/time of countdown
//Need to format only plural numbers with 's'
D:= FormatDateTime('d', DT)+' Days'; //Get number of days
H:= FormatDateTime('h', DT)+' Hours'; //Get number of hours
N:= FormatDateTime('n', DT)+' Minutes'; //Get number of minutes
S:= FormatDateTime('s', DT)+' Seconds'; //Get number of seconds
Str:= D+', '+H+', '+N+', '+S; //Build friendly string
if lblTitle.Caption <> Str then
lblTitle.Caption:= Str; //Update caption only if it's changed
end;
應該出來像...
0 Days, 3 Hours, 1 Minute, 12 Seconds
但相反的日子都出現了錯誤,當倒計時的日期/時間是今天的日期,它顯示30天......
30 Days, 3 Hours, 1 Minute, 12 Seconds
我想,如果我提前一個多月,它也不會正確顯示。我如何正確獲取天數? DateUtils單元中有沒有什麼能比我已經更好地自動化大部分工作?編輯: 固定!問題是我很愚蠢地用DT:= fDestDT - Now;
減去,這在我的第一個代碼片段中是正確的,但是在轉換爲使用DateUtils.DaysBetween
代替之後,我需要刪除該減法,並且僅設置DT:= Now;
。
工作代碼:
procedure TForm1.TmrTimer(Sender: TObject);
var
DT: TDateTime;
Days, Hours, Mins, Secs: Word;
SDays, SHours, SMins, SSecs: String;
Str: String;
begin
DT:= Now;
Days:= DaysBetween(DT, fDestDT);
Hours:= HoursBetween(fDestDT, DT) mod 24; // Remove total days
Mins:= MinutesBetween(DT, fDestDT) mod 60;
Secs := SecondsBetween(DT, fDestDT) mod 60;
if Days = 1 then SDays:= 'Day' else SDays:= 'Days';
if Hours = 1 then SHours:= 'Hour' else SHours:= 'Hours';
if Mins = 1 then SMins:= 'Minute' else SMins:= 'Minutes';
if Secs = 1 then SSecs:= 'Second' else SSecs:= 'Seconds';
Str:= Format('%d '+SDays+' %d '+SHours+' %d '+SMins+' %d '+SSecs,
[Days, Hours, Mins, Secs]);
if lblTime.Caption <> Str then
lblTime.Caption:= Str;
end;
我在這裏得到錯誤的秒數...把它放在一個計時器中,並實時觀察輸出 - 你會發現它不太正確,秒鐘總是出現在30秒以內。 –
是的,秒和分鐘應該是'mod 60'而不是'mod 24' –
已經完成了。發佈最後評論時必定發生。 :) –