program RelativeTime;
uses
SysUtils, DateUtils;
function ToRelativePastTime(dateTime: TDateTime): string;
var
nowTime: TDateTime;
deltaSec: Int64;
minutes, hours, days, months, years: Int64;
begin
nowTime := Now;
deltaSec := Abs(SecondsBetween(nowTime, dateTime));
minutes := deltaSec div 60;
hours := deltaSec div 3600;
days := deltaSec div 86400;
if deltaSec < 60 then
begin
if deltaSec = 1 then
Exit('one second ago')
else
Exit(IntToStr(deltaSec) + ' seconds ago');
end;
if deltaSec < 3600 then
begin
if minutes = 1 then
Exit('a minute ago')
else
Exit(IntToStr(minutes) + ' minutes ago');
end;
if deltaSec < 86400 then
begin
if hours = 1 then
Exit('an hour ago')
else
Exit(IntToStr(hours) + ' hours ago');
end;
if deltaSec < 2592000 then // 30 days
begin
if days = 1 then
Exit('yesterday')
else
Exit(IntToStr(days) + ' days ago');
end;
if deltaSec < 31104000 then // 12 months
begin
months := days div 30;
if months <= 1 then
Exit('a month ago')
else
Exit(IntToStr(months) + ' months ago');
end;
years := days div 365;
if years <= 1 then
Exit('a year ago')
else
Exit(IntToStr(years) + ' years ago');
end;
procedure Test(hoursAgo: Double);
var
past: TDateTime;
begin
past := IncSecond(Now, -Round(hoursAgo * 3600));
Writeln(ToRelativePastTime(past));
end;
begin
Test(0.01); // 36 seconds ago
Test(0.2); // 12 minutes ago
Test(3); // 3 hours ago
Test(25); // yesterday
Test(360); // 15 days ago
Test(1239); // a month ago
Test(2239); // 3 months ago
Test(8760); // a year ago
Test(98763); // 11 years ago
end.
(*
run:
36 seconds ago
12 minutes ago
3 hours ago
yesterday
15 days ago
a month ago
3 months ago
a year ago
11 years ago
*)