PHP时间计算

前端之家收集整理的这篇文章主要介绍了PHP时间计算前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有以下2个日期,开始日期和结束日期:
Year-Month-Day Hours:Minutes:Seconds  

Start Date:  2010-12-03 14:04:41
Expiry Date: 2010-12-06 12:59:59

我怎么能用PHP减去两个日期并留下类似的东西:

差异:-3天,2分18秒(例如,如果有效期超过3天).

这基于众多在线示例;如果你打开谷歌,你会看到类似的代码.
function timeSince($dateFrom,$dateTo) {
    // array of time period chunks
    $chunks = array(
        array(60 * 60 * 24 * 365,'year'),array(60 * 60 * 24 * 30,'month'),array(60 * 60 * 24 * 7,'week'),array(60 * 60 * 24,'day'),array(60 * 60,'hour'),array(60,'minute'),);

    $original = strtotime($dateFrom);
    $now      = strtotime($dateTo);
    $since    = $now - $original;
    $message  = ($now < $original) ? '-' : null;

    // If the difference is less than 60,we will show the seconds difference as well
    if ($since < 60) {
        $chunks[] = array(1,'second');
    }

    // $j saves performing the count function each time around the loop
    for ($i = 0,$j = count($chunks); $i < $j; $i++) {

        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];

        // finding the biggest chunk (if the chunk fits,break)
        if (($count = floor($since / $seconds)) != 0) {
            break;
        }
    }

    $print = ($count == 1) ? '1 ' . $name : $count . ' ' . $name . 's';

    if ($i + 1 < $j) {
        // now getting the second item
        $seconds2 = $chunks[$i + 1][0];
        $name2 = $chunks[$i + 1][1];

        // add second item if it's greater than 0
        if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
            $print .= ($count2 == 1) ? ',1 ' . $name2 : ',' . $count2 . ' ' . $name2 . 's';
        }
    }
    return $message . $print;
}

它旨在显示给定时间和当前时间之间的差异,但我做了一些细微的改动,以显示两次之间的差异.您可能希望将“之前”的后缀的输出更改为“差异:”的前缀.

原文链接:https://www.f2er.com/php/138517.html

猜你在找的PHP相关文章