我需要将 DateTime 转换为年、月、日、小时、分钟、秒前,就像 5 周前、1 年前或 1 个月前提出的 yahoo 问题一样,我的日期保存在数据库中,如下所示:2011-11-30 05:25:50。
现在我想在 PHP 中显示年、月、日、小时、分钟和秒,例如:how much year, how many months , days, hours, minutes, seconds之前,但只需要一个时间单位显示,就像年、天、小时、分钟或秒一样。
我已经搜索过这个问题,但不明白如何做到这一点,我知道 Stack Overflow 上这个主题有很多问题,也许它是重复的,但我无法解决我的问题。
提前致谢。
假设你的意思是相对于现在(如果你不这样做,请澄清你的问题),你可以使用这个:
$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)