Time ago strings...
Posted: Fri Feb 05, 2010 6:11 pm
For a couple of my internet apps that I've been working on, I've needed something nice that tells me how long ago something happened given an internet timestamp (whether from an RSS feed, my own PostgreSQL query, etc). Anyway, what I have turns out to be pretty nice and I thought I'd post it here in case anyone else could benefit from it.
Jeff M.
Code: Select all
function timeAgo pDate
local tNow, tDiff, tDay
-- convert the internet date to seconds
convert pDate to seconds
put pDate into tDay
-- make sure it is a valid date/timestamp
if the result is not empty then
return pDate
end if
-- figure out what day it is now
put the date into tNow
convert tNow to seconds
-- special case, check for "Today" when there is no time specified
if tNow - pDate is zero then
return "Today"
end if
-- extract just the date and convert it back
convert tDay to date
convert tDay to seconds
if tDay < tNow then
put (tNow - tDay) div (24 * 60 * 60) into tDiff
-- duration could be on the order of days, weeks, months, or years
if tDiff < 2 then
return "Yesterday"
else if tDiff < 7 then
return tDiff && "days ago"
else if tDiff < 14 then
return "1 week ago"
else if tDiff < 28 then
return (tDiff div 7) && "weeks ago"
else if tDiff < 56 then
return "1 month ago"
else if tDiff < 365 then
return (tDiff div 30) && "months ago"
else if tDiff < 730 then
return "1 year ago"
end if
-- a very long time ago, in a galaxy far away ;-)
return (tDiff div 365) && "years ago"
end if
-- get the number of seconds that have elapsed instead
put the seconds into tNow
put tNow - pDate into tDiff
-- duration could be seconds, minutes, or hours
if tDiff < 60 then
return "less than 1 minute ago"
else if tDiff < 120 then
return "1 minute ago"
else if tDiff < 60 * 60 then
return (tDiff div 60) && "minutes ago"
else if tDiff < 120 * 60 then
return "1 hour ago"
end if
-- several hours ago
return (tDiff div 3600) && "hours ago"
end timeAgo