微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/php/138517.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐