时间戳x小时前和24小时后的天数

时间:2016-07-28 19:38:01

标签: php html timestamp

我有这个代码,显示一个'主题'已发布,但它显示在几天,所以例如,如果它今天发布然后它将显示0天前..我怎么能让它显示它是否现在发布,例如1分钟前显示和增加后60小时,数小时,直到24小时,之后在几天内自动更改,就像现在一样。 我的代码:

<h4><span class="label label-default">
  <?php
  $start = date_create($row['timestamp']);
  $end = date_create();
  $diff=date_diff($end,$start);  
  print_r($diff->days);
  ?>
 day(s) ago</span></h4>

1 个答案:

答案 0 :(得分:1)

You could use this function:

function diffString($diff) {
    $units = ["year", "month", "day", "hour", "minute", "second"];
    $props = "ymdhis";
    foreach ($units as $i => $unit) {
        $prop = $props[$i];
        $num = $diff->$prop;
        if ($num) return "$num {$unit}" . ($num - 1 ? "s" : "");
    }
    return "0 seconds";
}

Example call:

$start = date_create('2016-07-28 16:23');
$end = date_create();
$diff=date_diff($end,$start);
echo diffString($diff) . " ago";

It will distinguish between singular and plural as well.