PHP:一小时前,x小时前

时间:2010-08-12 17:09:08

标签: php

所以我有这个函数来显示插入的unix格式时间戳(time())生成的时间:

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

我想扩展这个功能,如果它已经在24小时之内,它想要这样做,它应该计算并回显“x小时前”,如果它在昨天或之后,它应该像现在一样回声( echo“at:”。$ time;)..

如何做到这一点?

2 个答案:

答案 0 :(得分:5)

不到24小时前是3600 * 24,即

$time_now-3600*24

然后

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");

}

答案 1 :(得分:0)

/*
* @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;
}