How to calculate time passed with PHP or Zend_Date?

梦想与她 提交于 2019-12-06 15:37:31

问题


I'm trying to create a view helper that will display the number of minutes, hours, or days that have passed since...right now. I'm not really sure how to do it. It looks like the date comparison is working, but I don't know how to get the number. Here's what I have so far:

<?php

class Zend_View_Helper_RecentDate
{
    public function recentDate($datetime)
    {
        $date = new Zend_Date($datetime);

        switch ($date) {
            case($date->isEarlier(1, Zend_Date::HOUR)):
                $message = 'was minutes ago';
                break;
            case($date->isEarlier(24, Zend_Date::HOUR)):
                $message = 'was hours ago';
                break;
            case($date->isEarlier(48, Zend_Date::HOUR)):
                $message = 'Yesterday';
                break;
            default:
                $message = 'was days ago';
                break;
        }
        return $message;
    }
}

I want to replace "was" with the actual number of minutes/hours/days passed.


回答1:


Since you're already using the Zend Framework, there's a TimeSince view helper in the Zym Framework, which is a library of additional ZF extensions and helpers.

The TimeSince helper does basically exactly what you're trying to do:

Last updated <?= $this->timeSince($timestamp); ?> ago

Will output something like:

Last updated 8 hours ago



回答2:


$time = sprintf("%d hours, %d minutes and %d seconds\n", $s / (1000 * 60 * 60), $s / (1000 * 60), $s);

Where $s is seconds

assuming your $datetime is the unix timestamp you can get $ms from (time() - $timestamp)

if you want a full on fuzzy timestamp creator see: http://plugins.trac.wordpress.org/browser/splees-fuzzy-datetime/trunk/splees_fuzzy_datetime.php




回答3:


I have found Zend_Date alot easier to use with timestamp. Then format the output if you want (maybe use a view help to do that).

(this would have been a comment if I could)



来源:https://stackoverflow.com/questions/1639892/how-to-calculate-time-passed-with-php-or-zend-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!