tags:

views:

75

answers:

2

Hi. So i have this function to show the time generated from the inserted unix format timestamp(time()):

function get_time($timestamp) {
    $time = date('G:i', $timestamp);
    echo " at: ".$time;
    return $time;
}

I would like to expand this function and would like to do so if it has been under 24 hours, it should calculate and echo "x hours ago", if its yesterday or later, it should just echo like it does now ( echo " at: ".$time; ) ..

How can this be done?

+2  A: 

Less than 24 hours ago is 3600*24, i.e.

$time_now-3600*24

then

if($timestamp > (time() - (3600*24))) {

// Calculate time difference

$diff = time() - $timestamp;

$hours = $diff / 3600;

echo $hours . " hours ago";

} else {

echo "at" . date("x-y-z", $timestamp");

}
matiasf
time is in seconds, the division should be `$diff / (24 * 3600)`
Bob Fincheimer
couple of edits: dbl quotes by timestamp and $diff/3600 not 24. Otherwise a solid way to approach it; create a function and add a few options (..."days ago", 'Last Wednesday' etc) and you are in good shape.
Hans
@Hans: Tanks, updated the code. $diff/3600 is of course correct.
matiasf
@matiasf i just tested this code, and output i am getting is 0.584444444444 hours ago. Everytime i refresh the page the" 0.584444444444 hours ago" changes to other different value like 0.621666666667 and so on..?
Karem
@Karem: You should cast the $diff to an integer with intval($diff). For recent timestamps a separate check could be performed and a minute value echoed instead.
matiasf
@Matiasf this is not what ive wanted, i mean i wanted "round" numbers, 1 hour, 2 hour, not 0.863333333333 hours ago, (if under 1 hour then show in minutes) or forget the under hour, how do i round it to 1 or 2 numbers. $hours = intval($diff) / 3600 dont do any difference
Karem
intval($hours) did the work i wanted to do, thank you.
Karem
Why not just do "less than a hour ago" if it's < 1? That's what a lot of sites do. Or "About one day" etc. Just a long switch statement away from being whatever you need it to be.
Hans
A: 
/*
* @author Alexander.Plutov
* @param int $timestamp
* @param float $hours_ago
* @return date
*/
function get_time($timestamp, $hours_ago) {
    $seconds_ago = $hours_ago * 60 * 60 * 24;
    $new_timestamp = $timestamp - $seconds_ago;
    $time = date('G:i', $new_timestamp);
    echo " at: ".$time;
    return $time;
}
Alexander.Plutov