将日期时间转换为之前的时间

Muh*_*zad 1 php

我需要将 DateTime 转换为年、月、日、小时、分钟、秒前,就像 5 周前、1 年前或 1 个月前提出的 yahoo 问题一样,我的日期保存在数据库中,如下所示:2011-11-30 05:25:50

现在我想在 PHP 中显示年、月、日、小时、分钟和秒,例如:how much year, how many months , days, hours, minutes, seconds之前,但只需要一个时间单位显示,就像年、天、小时、分钟或秒一样。

我已经搜索过这个问题,但不明白如何做到这一点,我知道 Stack Overflow 上这个主题有很多问题,也许它是重复的,但我无法解决我的问题。

提前致谢。

Geo*_*ton 5

假设你的意思是相对于现在(如果你不这样做,请澄清你的问题),你可以使用这个:

$then = new DateTime('2011-11-30 05:25:50');
$now = new DateTime();
$delta = $now->diff($then);

$quantities = array(
    'year' => $delta->y,
    'month' => $delta->m,
    'day' => $delta->d,
    'hour' => $delta->h,
    'minute' => $delta->i,
    'second' => $delta->s);

$str = '';
foreach($quantities as $unit => $value) {
    if($value == 0) continue;
    $str .= $value . ' ' . $unit;
    if($value != 1) {
        $str .= 's';
    }
    $str .=  ', ';
}
$str = $str == '' ? 'a moment ' : substr($str, 0, -2);

echo $str;
Run Code Online (Sandbox Code Playgroud)

输出:

1 year, 9 months, 17 days, 14 hours, 31 minutes, 31 seconds
Run Code Online (Sandbox Code Playgroud)

  • 以正常方式从数据库中检索该时间戳,将“$result['asked_date']”放入第一个“DateTime”(“$then”)的构造函数中,并将“ago”附加到最后一个“$str”。 (2认同)
  • 是 - 不传递任何参数会将 DateTime 对象初始化为当前时间戳。 (2认同)
  • 有一种更简单的方法 - 请参阅我的编辑。`如果($value == 0) 继续;` (2认同)