我有两个表格日期:

Start Date: 2007-03-24 
End Date: 2009-06-26

现在,我需要通过以下形式找出这两者之间的区别:

2 years, 3 months and 2 days

如何在PHP中实现这一点?

推荐答案

将其用于遗留代码(PHP<;5.3).有关最新的解决方案,请参阅下面尤尔卡的答案

您可以使用strtotime()将两个日期转换为Unix时间,然后计算它们之间的秒数.由此可以相当容易地计算出不同的时间段.

$date1 = "2007-03-24";
$date2 = "2009-06-26";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

Edit:显然,这样做的首选方式如下所述.我的代码通常只在没有PHP5.3或更高版本的情况下推荐.

有几个人在 comments 中指出,上面的代码只是一个近似值.我仍然相信,对于大多数目的来说,这是可以的,因为使用范围更多的是为了提供已经过go 或剩余的时间的感觉,而不是提供精度-如果您想这样做,只需输出日期即可.

尽管如此,我还是决定处理这些投诉.如果您确实需要一个确切的范围,但无法访问PHP5.3,请使用下面的代码(它在PHP4中也应该可以工作).这是PHP内部用来计算范围的代码的直接移植,只是它没有考虑夏令时.这意味着它最多差一个小时,但除此之外,它应该是正确的.

<?php

/**
 * Calculate differences between two dates with precise semantics. Based on PHPs DateTime::diff()
 * implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved.
 * 
 * See here for original code:
 * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup
 * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&view=markup
 */

function _date_range_limit($start, $end, $adj, $a, $b, $result)
{
    if ($result[$a] < $start) {
        $result[$b] -= intval(($start - $result[$a] - 1) / $adj) + 1;
        $result[$a] += $adj * intval(($start - $result[$a] - 1) / $adj + 1);
    }

    if ($result[$a] >= $end) {
        $result[$b] += intval($result[$a] / $adj);
        $result[$a] -= $adj * intval($result[$a] / $adj);
    }

    return $result;
}

function _date_range_limit_days($base, $result)
{
    $days_in_month_leap = array(31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    $days_in_month = array(31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    _date_range_limit(1, 13, 12, "m", "y", &$base);

    $year = $base["y"];
    $month = $base["m"];

    if (!$result["invert"]) {
        while ($result["d"] < 0) {
            $month--;
            if ($month < 1) {
                $month += 12;
                $year--;
            }

            $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
            $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];

            $result["d"] += $days;
            $result["m"]--;
        }
    } else {
        while ($result["d"] < 0) {
            $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
            $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];

            $result["d"] += $days;
            $result["m"]--;

            $month++;
            if ($month > 12) {
                $month -= 12;
                $year++;
            }
        }
    }

    return $result;
}

function _date_normalize($base, $result)
{
    $result = _date_range_limit(0, 60, 60, "s", "i", $result);
    $result = _date_range_limit(0, 60, 60, "i", "h", $result);
    $result = _date_range_limit(0, 24, 24, "h", "d", $result);
    $result = _date_range_limit(0, 12, 12, "m", "y", $result);

    $result = _date_range_limit_days(&$base, &$result);

    $result = _date_range_limit(0, 12, 12, "m", "y", $result);

    return $result;
}

/**
 * Accepts two unix timestamps.
 */
function _date_diff($one, $two)
{
    $invert = false;
    if ($one > $two) {
        list($one, $two) = array($two, $one);
        $invert = true;
    }

    $key = array("y", "m", "d", "h", "i", "s");
    $a = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $one))));
    $b = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $two))));

    $result = array();
    $result["y"] = $b["y"] - $a["y"];
    $result["m"] = $b["m"] - $a["m"];
    $result["d"] = $b["d"] - $a["d"];
    $result["h"] = $b["h"] - $a["h"];
    $result["i"] = $b["i"] - $a["i"];
    $result["s"] = $b["s"] - $a["s"];
    $result["invert"] = $invert ? 1 : 0;
    $result["days"] = intval(abs(($one - $two)/86400));

    if ($invert) {
        _date_normalize(&$a, &$result);
    } else {
        _date_normalize(&$b, &$result);
    }

    return $result;
}

$date = "1986-11-10 19:37:22";

print_r(_date_diff(strtotime($date), time()));
print_r(_date_diff(time(), strtotime($date)));

Php相关问答推荐

WooCommerce拆分运输包裹上的商品数量增加运输成本

Laravel 10查询中的多个where子句

如何在WordPress中为特定自定义帖子类型自定义URL struct

从WooCommerce Checkout Country Select2下拉列表中重新排序国家/地区

如何使用`preg_replace`删除重复的空格字符

向在添加到购物车上动态创建的WooCommerce产品添加发货类别

在没有谷歌云客户端PHP库的情况下将图像上传到PHP中的Google存储API?

Laravel Livewire如何在数组值上使用IF、ELSE条件

WooCommerce我的帐户:从帖子作者处获取自定义帖子类型帖子ID

SendGrid响应PHP

PHP -流加密启用服务器切断字节

Laravel 10中的Validator类

在PHP项目中安装OpenAI PHP SDK时出现问题

为WooCommerce中存储一些数据的购物车项目添加复选框

将 PHP 版本更改为 8.1,但 WordPress 认为我们正在使用版本 7.4?

标签打印机的 CSS

URL中包含"&"与DirectoryIterator不兼容

CodeIgniter 4中嵌套过滤器组不起作用

Woocommerce注册中的自定义复选框验证错误提示问题

用于检测此模式的正则表达式:something;something=something,something=something... 未知次数