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

时间:2022-08-19 21:28:44

Are there any classes/functions written in php publicly available that will take a timestamp, and return the time passed since then in number of days, months, years etc? Basically i want the same function that generates the time-since-posted presented together with each entry on this site (and on digg and loads of other sites).

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

5 个解决方案

#1


This is written as a wordpress plugin but you can extract the relevant PHP code no problem: Fuzzy date-time

这是一个wordpress插件,但你可以提取相关的PHP代码没有问题:模糊日期时间

#2


Here is a Zend Framework ViewHelper I wrote to do this, you could easily modify this to not use the ZF specific code:

这是我写的一个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
        );
    }
}

#3


I'm not sure there will be classes for that but I've found on Google a couple of methods to achieve what you want:

我不确定会有课程,但我在Google上找到了几种方法来实现你想要的东西:

Maybe one of them fits or needs or you can easily adapt it.

也许其中一个适合或需要,或者您可以轻松地适应它。

#4


Brother Google knows the answer:

谷歌兄弟知道答案:

This has been asked before:

之前有人问过:

How to calculate the difference between two dates using PHP?

如何使用PHP计算两个日期之间的差异?

This is the best version I have seen (for human readable format):

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

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

PHP 5+ has something now built in:

PHP 5+现在内置了一些内容:

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

I personally was looking for calculating the number of days (as a decimal) so I can then subset into years, etc.

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

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;
    }

#5


This function returns a numeric array. You may extract years, months, days, hours, minutes and seconds. e.g. echo $result[3] gets you hours and echo $result[4] gets you minutes. (I have borrowed this code). cheers!

此函数返回一个数字数组。您可以提取年,月,日,小时,分钟和秒。例如echo $ result [3]可以获得小时数和回声$结果[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;
    }

#1


This is written as a wordpress plugin but you can extract the relevant PHP code no problem: Fuzzy date-time

这是一个wordpress插件,但你可以提取相关的PHP代码没有问题:模糊日期时间

#2


Here is a Zend Framework ViewHelper I wrote to do this, you could easily modify this to not use the ZF specific code:

这是我写的一个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
        );
    }
}

#3


I'm not sure there will be classes for that but I've found on Google a couple of methods to achieve what you want:

我不确定会有课程,但我在Google上找到了几种方法来实现你想要的东西:

Maybe one of them fits or needs or you can easily adapt it.

也许其中一个适合或需要,或者您可以轻松地适应它。

#4


Brother Google knows the answer:

谷歌兄弟知道答案:

This has been asked before:

之前有人问过:

How to calculate the difference between two dates using PHP?

如何使用PHP计算两个日期之间的差异?

This is the best version I have seen (for human readable format):

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

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

PHP 5+ has something now built in:

PHP 5+现在内置了一些内容:

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

I personally was looking for calculating the number of days (as a decimal) so I can then subset into years, etc.

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

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;
    }

#5


This function returns a numeric array. You may extract years, months, days, hours, minutes and seconds. e.g. echo $result[3] gets you hours and echo $result[4] gets you minutes. (I have borrowed this code). cheers!

此函数返回一个数字数组。您可以提取年,月,日,小时,分钟和秒。例如echo $ result [3]可以获得小时数和回声$结果[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;
    }