How to calculate time passed with PHP or Zend_Date

2019-04-16 18:21发布

问题:

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)