【问题标题】:Subtracting time to post how many minutes ago [duplicate]减去几分钟前发布的时间[重复]
【发布时间】:2014-12-05 01:07:25
【问题描述】:

所以我当前的 $item['date'] 函数以Y-m-d H:i:s这种格式获取帖子的时间和日期。

我想显示帖子发布了多少分钟,或者如果超过 24 小时,它是在几天前发布的,或者像 0 天和 20 小时前一样?类似的东西

为什么减号运算符在我的代码中不起作用?

我当前的代码:

<p><?php echo date('Y-m-d H:i:s') - $item['date'] ?> minutes ago</p>

【问题讨论】:

    标签: php function time subtraction


    【解决方案1】:

    我通常使用这个功能。像这样使用time_ago('2014-12-03 16:25:26')

    function time_ago($date){
        $retval = NULL;
        $granularity=2;
        $date = strtotime($date);
        $difference = time() - $date;
        $periods = array('decade' => 315360000,
            'year' => 31536000,
            'month' => 2628000,
            'week' => 604800, 
            'day' => 86400,
            'hour' => 3600,
            'minute' => 60,
            'second' => 1);
    
        foreach ($periods as $key => $value) 
        {
            if ($difference >= $value) 
            {
                $time = round($difference/$value);
                $difference %= $value;
                $retval .= ($retval ? ' ' : '').$time.' ';
                $retval .= (($time > 1) ? $key.'s' : $key);
                $granularity--;
            }
            if ($granularity == '0') { break; }
        }
        return $retval.' ago';      
    }
    

    【讨论】:

      【解决方案2】:

      您需要做的是首先将两个日期都转换为时间戳,然后从当前日期中减去您的原始发布日期,然后将其重新转换回您想要的格式。如下所示。

      $now = time();
      $datePosted = strtotime($item['date']);
      
      $timePassed = $now - $datePosted;
      
      $agoMinutes = $timePassed/60; //this will give you how many minutes passed
      $agoHours = $agoMinutes/60; //this will give you how many hours passed
      $agoDays = $agoHours/24; // this will give you how many days passed
      

      等等……

      Php 的时间戳以秒为单位提供日期,因此如果您需要数学运算,则更容易计算和处理它。

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 2018-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-06
        相关资源
        最近更新 更多