tags:

views:

768

answers:

6

Looking for the best pseudo-code to generate a relative date string (ex. 'asked 1 minute ago', 'asked 2 days ago', 'asked 3 weeks ago', 'asked 4 months ago'...).

Currently implementing this myself and thought it would be a good programming exercise for those that have not tried this before.

Ryan

Edit: I did search before posting and it didn't turn up any results.

+1  A: 

You can probably find the solution in this post:

http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time

Serhat Özgel
+1  A: 

This question was asked...http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time

Unkwntech
A: 

Someone with rights, please close this question.

DevelopingChris
A: 

Get Timespan from DateInserted and Now.
If TimeSpan is Less than 1 hour then Display Difference in minutes
If TimeSpan is Greater Than 1 Hour and Less than 1 day get difference in Hours
If TimeSpan is Greater than 1 Day but Less than 1 Week get difference in Days
If TimeSpan is Greater than 1 Week but Less than 1 Month get difference in Weeks
If TimeSpan is Greater than 1 Month, but less than 1 Year get difference in Months
If TimeSpan is Greater than 1 YEar but less than a decade....

Stephen Wrighton
A: 

Once you have the time difference (let's say in seconds) you could do something like this:

time_diff # holds the time difference in seconds

for period in [year, month, day, hour, minute, second]:
    nper = time_diff/seconds_in(period)
    if ( nper > 0 )
         print nper + period + " ago"
         break from the loop;

This is a simple example but it can be improved.

For example if you want to be more exact (eg: 1 year 2 months and 3 days) you could go further and send the remainder ( ) for extra analysys.

Iulian Şerbănoiu
A: 

I'm basing it on Unix timestamps here, also, I'm approximating the length of months and years, because I can't imagine any case where you'd need to be absolutely precise, yet write the date in such way.

Delta := CurrentTimestamp - OldTimestamp

Timespans := [year: 31557600, month: 2629800, week: 604800, day: 86400, hour: 3600, minute: 60]

Result := "Asked "

for each Name, Seconds in Timespans
    Result := Result + Delta div Seconds + "  " + Name
    Delta := Delta mod Seconds

Result := Result + " ago"
Print Result
Nouveau