0

我试图将 mysql 时间戳转换为几个月或几天或几小时或几分钟的时间。

所以输出将如下所示:

添加于 1 个月前 / 添加: 0 小时前 / 添加: 21 分钟前 / 添加于 30 秒前

所以我只想要一种时间格式,具体取决于多少分钟或多少小时或多少天等,因此 60 分钟转换为 1 小时前或 24 小时转换为 1 天前,48 小时转换为 2 天前。

到目前为止我有这个代码:

<?
    $datetime1 = new DateTime();
    $datetime2 = new DateTime ($news['date_added']);
    $interval = $datetime1->diff($datetime2);
    str_replace('0 hours', '', $variable);
    echo $interval->format('%h hours %i minutes');
    ?>

这将输出以下内容:

添加于 0 小时前 57 分钟前。

有人可以帮助我或告诉我需要做什么才能使格式正确显示,我对 php 真的很陌生,我不确定我该怎么做。谢谢你。

4

2 回答 2

3

来自http://php.net/manual/en/ref.datetime.php

只需在调用函数时将 $precision 更改为 1 并在日期之前和之后添加您想要的任何文本。您必须确保将日期对象转换为时间戳,但这对您来说应该不是问题。

/**
 * this code assumes php >= 5.1.0. if using < 5.1, read
 * php.net/strtotime and change the condition for checking
 * for failure from strtotime()
 */

// $t1, $t2: unix times, or strtotime parseable
// $precision: max number of units to output
// $abbr: if true, use "hr" instead of "hour", etc.
function date_diff ($t1, $t2, $precision = 6, $abbr = false) {
    if (preg_match('/\D/', $t1) && ($t1 = strtotime($t1)) === false)
        return false;

    if (preg_match('/\D/', $t2) && ($t2 = strtotime($t2)) === false)
        return false;

    if ($t1 > $t2)
        list($t1, $t2) = array($t2, $t1);

    $diffs = array(
        'year' => 0, 'month' => 0, 'day' => 0,
        'hour' => 0, 'minute' => 0, 'second' => 0,
    );

    $abbrs = array(
        'year' => 'yr', 'month' => 'mth', 'day' => 'day',
        'hour' => 'hr', 'minute' => 'min', 'second' => 'sec'
    );

    foreach (array_keys($diffs) as $interval) {
        while ($t2 >= ($t3 = strtotime("+1 ${interval}", $t1))) {
            $t1 = $t3;
            ++$diffs[$interval];
        }
    }

    $stack = array();
    foreach ($diffs as $interval => $num)
        $stack[] = array($num, ($abbr ? $abbrs[$interval] : $interval) . ($num != 1 ? 's' : ''));

    $ret = array();
    while (count($ret) < $precision && ($item = array_shift($stack)) !== null) {
        if ($item[0] > 0)
            $ret[] = "{$item[0]} {$item[1]}";
    }

    return implode(', ', $ret);
}

$t1 = 'Feb 4, 2008 12:16:00';
$t2 = 'Jul 3, 2006 16:15:30';

echo date_diff($t1, $t2), "\n",
    date_diff($t1, $t2, 3), "\n",
    date_diff($t1, $t2, 2, true), "\n";

?>
于 2013-02-04T17:37:22.680 回答
1

这是一个可能的解决方案。您将时差格式化为带有月-日-小时-分钟-秒的字符串,然后查看该字符串以查找第一个非零数字:这就是您想要的...

$mdhms = explode('-',$interval->format('%m-%d-%H-%i-%s'));

$labels = Array(' months', ' days', ' hours', ' minutes', ' seconds');
$i = 0;
foreach($mdhms as $t){
  if($t > 0) break;
  $i+=1;
}
if ($i < 5) echo "It happened ".$t.$labels[$i]." ago";
else echo "It is happening right now!"
于 2013-02-04T17:46:16.687 回答