Code:
uses
SysUtils;
const
// Modify these to change the language
CYears = 'year(s)';
CDays = 'day(s)';
// Just in case some Delphi version misses these constants
HoursPerDay = 24;
MinsPerDay = HoursPerDay * 60;
SecsPerDay = MinsPerDay * 60;
SecsPerMin = 60;
SecsPerHour = SecsPerMin * 60;
// Extract the number of days/hours/etc from the input in seconds
procedure SecondsToTime(const AInput: Integer; var ASeconds, AMinutes, AHours,
ADays, AYears: Integer);
function SubtractSeconds(var ASeconds: Integer; ASize: Integer): Integer;
begin
// How many times does ASize fit in ASeconds?
Result := ASeconds div ASize;
Dec(ASeconds, Result * ASize);
end;
var
iSeconds: Integer;
begin
iSeconds := AInput;
AYears := SubtractSeconds(iSeconds, SecsPerDay * 365);
ADays := SubtractSeconds(iSeconds, SecsPerDay);
AHours := SubtractSeconds(iSeconds, SecsPerHour);
AMinutes := SubtractSeconds(iSeconds, SecsPerMin);
ASeconds := iSeconds;
end;
// Uses SecondsToTime to make a nice ready-for-display string
//
// Format:
// %y Years
// %d Days
// %h Hours (%hh = force 2 digits, ex: 04)
// %m Minutes (%mm = force 2 digits)
// %s Seconds (%ss = force 2 digits)
function SecondsToString(const ASeconds: Integer;
const AFormat: String = ''): String;
const
CReplaceFlags = [rfReplaceAll, rfIgnoreCase];
var
iYears: Integer;
iDays: Integer;
iHours: Integer;
iMinutes: Integer;
iSeconds: Integer;
begin
Result := '';
SecondsToTime(ASeconds, iSeconds, iMinutes, iHours, iDays, iYears);
if Length(AFormat) = 0 then
// No format specified, build our own format
if iYears > 0 then
Result := Format('%d %s, %d %s, %.2d:%.2d:%.2d', [iYears, CYears,
iDays, CDays,
iHours, iMinutes,
iSeconds])
else if iDays > 0 then
Result := Format('%d %s, %.2d:%.2d:%.2d', [iDays, CDays,
iHours, iMinutes,
iSeconds])
else
Result := Format('%.2d:%.2d:%.2d', [iHours, iMinutes, iSeconds])
else begin
// Use the specified format explicitly
Result := AFormat;
Result := StringReplace(Result, '%y', IntToStr(iYears), CReplaceFlags);
Result := StringReplace(Result, '%d', IntToStr(iDays), CReplaceFlags);
Result := StringReplace(Result, '%hh', Format('%.2d', [iHours]), CReplaceFlags);
Result := StringReplace(Result, '%h', IntToStr(iHours), CReplaceFlags);
Result := StringReplace(Result, '%mm', Format('%.2d', [iMinutes]), CReplaceFlags);
Result := StringReplace(Result, '%m', IntToStr(iMinutes), CReplaceFlags);
Result := StringReplace(Result, '%ss', Format('%.2d', [iSeconds]), CReplaceFlags);
Result := StringReplace(Result, '%s', IntToStr(iSeconds), CReplaceFlags);
end;
end;
Bookmarks