0

For example, when you submit a post it might say "submitted 1 second ago." and if it was 2 weeks old it would say that. Did SO and Reddit write these or is there a PHP/SQL function that converts the date in to a more human readable and relevant format such as this?

John Smith
  • 8,567
  • 13
  • 51
  • 74
  • see this http://stackoverflow.com/questions/5300050/so-dates-calculation-and-formating/5300051#5300051 – Nishant Mar 18 '11 at 04:35

3 Answers3

2

I'd highly suggest checking out John Resig's pretty date library:

http://ejohn.org/blog/javascript-pretty-date/

As shown on that blog post, you can do things like this:

prettyDate("2008-01-28T20:24:17Z") // => "2 hours ago"
prettyDate("2008-01-27T22:24:17Z") // => "Yesterday"
prettyDate("2008-01-26T22:24:17Z") // => "2 days ago"
prettyDate("2008-01-14T22:24:17Z") // => "2 weeks ago"
prettyDate("2007-12-15T22:24:17Z") // => undefined 
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
1

They are called fuzzy dates/times and there are many libraries for JavaScript and PHP.

alex
  • 479,566
  • 201
  • 878
  • 984
0

there's lots of ways todo it but if you want to use php then this function will output it in a nice way just put a unix timestamp in

function timeDiffrence($from, $to = null){
    $to = (($to === null) ? (time()) : ($to));
    $to = ((is_int($to)) ? ($to) : (strtotime($to)));
    $from = ((is_int($from)) ? ($from) : (strtotime($from)));
    $units = array
    (
    " Years"   => 29030400, // seconds in a year   (12 months)
    " Months"  => 2419200,  // seconds in a month  (4 weeks)
    " Weeks"   => 604800,   // seconds in a week   (7 days)
    " Days"    => 86400,    // seconds in a day    (24 hours)
    " Hours"   => 3600,     // seconds in an hour  (60 minutes)
    " Minute" => 60,       // seconds in a minute (60 seconds)
    " Second" => 1         // 1 second
    );
    $diff = abs($from - $to);
    $suffix = (($from > $to) ? (" from now") : (" "));
    foreach($units as $unit => $mult)
    if($diff >= $mult)
    {
        $and = (($mult != 1) ? ("") : ("and "));
        $output .= "".$and.intval($diff / $mult)."".$unit.((intval($diff / $mult) == 1) ? (", ") : ("'s, "));
        $diff -= intval($diff / $mult) * $mult;
    }
    $output .= " ".$suffix;
    $output = substr($output, strlen(""));
    if($output =='go' || $output ==' ago'){$output = 'A few secs ago';}
    return 'Posted '.str_ireplace('1 Days','1 Day',trim($output,', ')).' ago';
}
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106