program DateTimes;
{$mode Delphi}
uses SysUtils, DateUtils;
function DateTimeToReadableString(const TimeThen, TimeNow: TDateTime; Padding: boolean = False): String;
var
fDifference: TDateTime;
fYears, fMonths, fDays: Word;
fHours, fMinutes, fSeconds, fMilliSeconds: Word;
fYearsStr, fMonthsStr, fDaysStr: String;
fHourStr, fMinutesStr, fSecondsStr: String;
begin
Result := '';
fDifference := TimeNow - TimeThen;
DecodeDate(fDifference, fYears, fMonths, fDays);
// the values from DecodeDate are not correct
fYears := YearsBetween(TimeNow, TimeThen);
fMonths := MonthsBetween(TimeNow, TimeThen);
DecodeTime(fDifference, fHours, fMinutes, fSeconds, fMilliSeconds);
if fYears > 0 then
begin
if Padding then
fYearsStr := Format('%2d', [fYears])
else
fYearsStr := Format('%d', [fYears]);
if fYears > 1 then
fYearsStr := fYearsStr + ' years'
else
fYearsStr := fYearsStr + ' year';
end;
if fMonths > 0 then
begin
if Padding then
fMonthsStr := Format('%2d', [fMonths])
else
fMonthsStr := Format('%d', [fMonths]);
if fMonths > 1 then
fMonthsStr := fMonthsStr + ' months'
else
fMonthsStr := fMonthsStr + ' month';
end;
if fDays > 0 then
begin
if Padding then
fDaysStr := Format('%2d', [fDays])
else
fDaysStr := Format('%d', [fDays]);
if fDays > 1 then
fDaysStr := fDaysStr + ' days'
else
fDaysStr := fDaysStr + ' day';
end;
if fHours > 0 then
begin
if Padding then
fHourStr := Format('%2d', [fHours])
else
fHourStr := Format('%d', [fHours]);
if fHours > 1 then
fHourStr := fHourStr + ' hours'
else
fHourStr := fHourStr + ' hour';
end;
if fMinutes > 0 then
begin
if Padding then
fMinutesStr := Format('%2d', [fMinutes])
else
fMinutesStr := Format('%d', [fMinutes]);
if fMinutes > 1 then
fMinutesStr := fMinutesStr + ' minutes'
else
fMinutesStr := fMinutesStr + ' minute';
end;
if fSeconds > 0 then
begin
if Padding then
fSecondsStr := Format('%2d', [fSeconds])
else
fSecondsStr := Format('%d', [fSeconds]);
if fSeconds > 1 then
fSecondsStr := fSecondsStr + ' seconds'
else
fSecondsStr := fSecondsStr + ' second';
end;
if fYearsStr <> '' then
Result := fYearsStr;
if fMonthsStr <> '' then
Result := Result + ' ' + fMonthsStr;
if fDaysStr <> '' then
Result := Result + ' ' + fDaysStr;
if fHourStr <> '' then
Result := Result + ' ' + fHourStr;
if fMinutesStr <> '' then
Result := Result + ' ' + fMinutesStr;
if fSecondsStr <> '' then
Result := Result + ' ' + fSecondsStr;
if not Padding then
Result := Trim(Result);
end;
var
x: TDateTime;
begin
writeln('Hello, world!');
x := Now;
Sleep(2000);
writeln(DateTimeToReadableString(x, Now));
Sleep(6000);
writeln(DateTimeToReadableString(x, Now));
writeln('Bye, world!');
end.