计算两个日期之间的时差,并显示答案,如“2天3小时前”

时间:2009-01-11 04:56:57

标签: php date

是否有公开的PHP公开的类/函数需要时间戳,并返回自那时以来的天数,月数,年数等等?基本上我想要生成与本网站上的每个条目(以及其他网站的挖掘和加载)一起呈现的自发布时间的相同功能。

5 个答案:

答案 0 :(得分:3)

这是一个wordpress插件,但你可以提取相关的PHP代码没问题:Fuzzy date-time

答案 1 :(得分:3)

这是我写的一个Zend Framework ViewHelper,你可以很容易地修改它以不使用ZF特定的代码:

/**
 * @category    View_Helper
 * @package     Custom_View_Helper
 * @author      Chris Jones <leeked@gmail.com>
 * @license     New BSD License
 */
class Custom_View_Helper_HumaneDate extends Zend_View_Helper_Abstract
{
    /**
     * Various time formats
     */
    private static $_time_formats = array(
        array(60, 'just now'),
        array(90, '1 minute'),                  // 60*1.5
        array(3600, 'minutes', 60),             // 60*60, 60
        array(5400, '1 hour'),                  // 60*60*1.5
        array(86400, 'hours', 3600),            // 60*60*24, 60*60
        array(129600, '1 day'),                 // 60*60*24*1.5
        array(604800, 'days', 86400),           // 60*60*24*7, 60*60*24
        array(907200, '1 week'),                // 60*60*24*7*1.5
        array(2628000, 'weeks', 604800),        // 60*60*24*(365/12), 60*60*24*7
        array(3942000, '1 month'),              // 60*60*24*(365/12)*1.5
        array(31536000, 'months', 2628000),     // 60*60*24*365, 60*60*24*(365/12)
        array(47304000, '1 year'),              // 60*60*24*365*1.5
        array(3153600000, 'years', 31536000),   // 60*60*24*365*100, 60*60*24*365
    );

    /**
     * Convert date into a pretty 'human' form
     *      Now with microformats!
     *
     * @param string|Zend_Date $date_from Date to convert
     * @return string
     */
    public function humaneDate($date_from)
    {
        $date_to = new Zend_Date(null, Zend_Date::ISO_8601);

        if (!($date_from instanceof Zend_Date)) {
            $date_from = new Zend_Date($date_from, Zend_Date::ISO_8601);
        }

        $dateTo     = $date_to->getTimestamp();   // UnixTimestamp
        $dateFrom   = $date_from->getTimestamp(); // UnixTimestamp
        $difference = $dateTo - $dateFrom;
        $message    = '';

        if ($dateFrom <= 0) {

            $message = 'a long time ago';

        } else {

            foreach (self::$_time_formats as $format) {

                if ($difference < $format[0]) {

                    if (count($format) == 2) {
                        $message = $format[1] . ($format[0] === 60 ? '' : ' ago');
                        break;
                    } else {
                        $message = ceil($difference / $format[2]) . ' ' . $format[1] . ' ago';
                        break;
                    }

                }
            }

        }

        return sprintf('<abbr title="%sZ">%s</abbr>',
            $date_from->get('YYYY-MM-ddTHH:mm:ss'),
            $message
        );
    }
}

答案 2 :(得分:1)

我不确定是否会有课程,但我在Google上找到了几种方法来实现您的目标:

也许其中一个适合或需要,或者你可以很容易地适应它。

答案 3 :(得分:0)

谷歌兄弟知道答案:

之前有人问过:

How to calculate the difference between two dates using PHP?

这是我见过的最好的版本(人类可读格式):

http://www.if-not-true-then-false.com/2010/php-calculate-real-differences-between-two-dates-or-timestamps/

PHP 5+现已内置:

http://php.net/manual/en/datetime.diff.php

我个人正在寻找计算天数(十进制),以便我可以将其分为几年等等。

function daysDifference($d1,$d2)
    {
    $ts2    =   strtotime($d1);
    $ts1    =   strtotime($d2);
        $seconds    = abs($ts2 - $ts1); # difference will always be positive
    $days = $seconds/60/60/24;
    return $days;
    }

答案 4 :(得分:0)

此函数返回一个数字数组。您可以提取年,月,日,小时,分钟和秒。例如echo $ result [3]可以获得小时数和echo $ result [4]获得分钟数。 (我借用了这段代码)。干杯!

function dateDiff($time1, $time2, $precision = 6)
    {
        // If not numeric then convert texts to unix timestamps
        if (!is_int($time1)) {
            $time1 = strtotime($time1);
        }
        if (!is_int($time2)) {
            $time2 = strtotime($time2);
        }

        // If time1 is bigger than time2
        // Then swap time1 and time2
        if ($time1 > $time2) {
            $ttime = $time1;
            $time1 = $time2;
            $time2 = $ttime;
        }

        // Set up intervals and diffs arrays
        $intervals = array('year', 'month', 'day', 'hour', 'minute', 'second');
        $diffs     = array();

        // Loop thru all intervals
        foreach ($intervals as $interval) {
            // Set default diff to 0
            $diffs[$interval] = 0;
            // Create temp time from time1 and interval
            $ttime = strtotime("+1 " . $interval, $time1);
            // Loop until temp time is smaller than time2
            while ($time2 >= $ttime) {
                $time1 = $ttime;
                $diffs[$interval]++;
                // Create new temp time from time1 and interval
                $ttime = strtotime("+1 " . $interval, $time1);
            }
        }

        $count = 0;
        $times = array();
        // Loop thru all diffs
        foreach ($diffs as $interval => $value) {
            // Break if we have needed precission
            if ($count >= $precision) {
                break;
            }
            // Add value and interval
            // if value is bigger than 0
            if ($value >= 0) {
                // Add s if value is not 1
                if ($value != 1) {
                    $interval .= "s";
                }
                // Add value and interval to times array
                $times[] = $value; // . " " . $interval;
                $count++;
            }
        }

        // Return string with times
        //return implode(", ", $times);
        return $times;
    }