【发布时间】:2026-02-20 08:20:08
【问题描述】:
我正在使用一个函数(在网上找到它)来计算到现在为止的时间。我传递了两个参数:发布日期和当前日期。它将返回年、月、日、小时、分钟或秒。它使用 PHP 5.3 的 date diff 函数,这在 5.2 版本中是不会的 :(
function pluralize( $zaehler, $inhalt ) {
return trim($zaehler . ( ( $zaehler == 1 ) ? ( " $inhalt" ) : ( " ${inhalt}s" ) )." ago");}function ago($datetime, $datetime_post){
$interval = date_create($datetime_post)->diff( date_create($datetime) );
if ( $interval->y >= 1 ) return pluralize( $interval->y, 'year' );
if ( $interval->m >= 1 ) return pluralize( $interval->m, 'month' );
if ( $interval->d >= 1 ) return pluralize( $interval->d, 'day' );
if ( $interval->h >= 1 ) return pluralize( $interval->h, 'hour' );
if ( $interval->i >= 1 ) return pluralize( $interval->i, 'minute' );
if ( $interval->s >= 1 ) return pluralize( $interval->s, 'second' );}
示例:
$post_date_time = "01/01/2012 11:30:22";
$current_date_time = "02/02/2012 07:35:41";
echo ago($current_date_time, $post_date_time);
将输出:
1 month
现在我需要一个等效的函数“ago”来做同样的事情,具体取决于 $interval 对象。
非常感谢
附加信息: 提供的解决方案都没有真正做到我想要的。我必须改进我的解释,对不起。 最后,我只需要 $interval 对象即可:
object(DateInterval)#3 (8) { ["y"]=> int(0) ["m"]=> int(1) ["d"]=> int(0) ["h"]=> int(20) ["i"]=> int(5) ["s"]=> int(19) ["invert"]=> int(0) ["days"]=> int(6015) }
没有必要改变这么多东西。
【问题讨论】:
-
你不能用*.com/questions/676824/…吗?
-
另外,如果您不知道,您可以使用 PHP 的
date( ... )函数获取当前日期时间:php.net/manual/en/function.date.php -
很容易得到两个日期的差异,以秒为单位。将秒转换为小时、分钟和天是微不足道的。转换为月和年……如果您假设每个月有 30 天并且每年有 12 个 30 天的月份,那么这很容易。这个解决方案可以接受吗?
-
你可能想看看 Zend Framework 的 Zend_Date-component:framework.zend.com/manual/en/… 明确一点,你不需要完整的 Zend Framework,只需要 Zend/Date.php,Zend/Date/和 Zend/Locale.php(依赖)。那么你应该可以在你的代码中使用
new Zend_Date()... -
@vivid-colours:谢谢,很遗憾没有。我期望的输出应该只有一种类型,例如“2 个月前”或“34 分钟前”。和 twitter/fb 一样。
标签: php datetime datediff php-5.2