phpmysqltimetimestamprelative-date

How to get timestamp of MySQL table in relative time on website


I want to know, step by step, the way to transform a timestamp in my mysql table to a relative time (4 seconds ago, 5 months ago...) on my website.

For information, my timestamp column is named creation, and my table is named users.

The code I tried:

function relativedate($secs) {
    $second = 1;
    $minute = 60;
    $hour = 60*60;
    $day = 60*60*24;
    $week = 60*60*24*7;
    $month = 60*60*24*7*30;
    $year = 60*60*24*7*30*365;

    if ($secs <= 0) { $output = "now";
    }elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
    }elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
    }elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
    }elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
    }elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
    }elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
    }elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
    }else{ $output = " more than a decade ago"; }

    if ($output <> "now"){
        $output = (substr($output,0,2)<>"1 ") ? $output."s" : $output;
    }
    return $output;
}



echo relativedate(60); // 1 minute

Solution

  • Use CASE to display the relative time/date. I created the table 'sample' in this code.

    SELECT *, CASE
    WHEN creation between date_sub(now(), INTERVAL 60 minute) and now() THEN concat(minute(TIMEDIFF(now(), creation)), ' minutes ago')
    WHEN datediff(now(), creation) = 1 THEN 'Yesterday'
    WHEN creation between date_sub(now(), INTERVAL 24 hour) and now() THEN concat(hour(TIMEDIFF(NOW(), creation)), ' hours ago')
    ELSE date_format(creation, '%a, %m/%d/%y')
    END as date FROM sample 
    

    This will make a new column 'date' that you can use to output the relative time.