首页 > 解决方案 > 如何将时间前功能限制在 12 个月以下并发布一年或更晚的实际日期?

问题描述

我想发布一篇文章的实际日期(即 2015 年 4 月 5 日),如果它自发布以来已经一年或更长时间。如果不到一年,我想使用时间前功能(即 6 个月前)。

我尝试在 HumanTiming Time Ago Function 中注释掉年份(由 arnorhs 发布)并向其添加 if/else 条件

$time = strtotime('2015-04-05 17:25:43');

echo 'event happened '.humanTiming($time).' ago';

function humanTiming ($time)
{

    $time = time() - $time; // to get the time since that moment
    $time = ($time<1)? 1 : $time;
    $tokens = array (
        //31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    if($time > $tokens){ 
        echo "April 5, 2015"; 
    } else {
        foreach ($tokens as $unit => $text) {
            if ($time < $unit) continue;
                $numberOfUnits = floor($time / $unit);
                return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
         }
     }
}

我希望输出为“2015 年 4 月 5 日”,但它忽略了 if/else 条件并将日期发布为“36 个月前”。

我怎样才能达到我想要的结果?

标签: php

解决方案


使用 DateTime 更简单

$now = new DateTime();

$then = new DateTime('April 5, 2015');

$diff = $now->diff($then); // returns DateInterval object or false on failure

if ($diff->y >= 1) {
    // show your date
    echo $then->format('Y-m-d H:i:s');
} else {
    // show the interval
    echo $diff->format('%d days ago');
}

查看文档以获取更多信息

https://www.php.net/manual/en/class.dateinterval.php

https://www.php.net/manual/en/dateinterval.format.php


推荐阅读