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

819

我有两个日期,格式如下:

Start Date: 2007-03-24 
End Date: 2009-06-26
现在我需要以以下形式找到这两者之间的差异:
2 years, 3 months and 2 days

我该如何用PHP实现这个功能?


3
2年94天。考虑到闰年计算月份将会有问题。需要多准确呢? - dbasnett
可能是重复的问题:如何计算相对时间? - Cole Tobin
34个回答

1034
我建议使用DateTime和DateInterval对象。
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

阅读更多 php DateTime::diff 手册

来自手册:

从 PHP 5.2.2 [2007年5月] 开始,可以使用比较运算符比较 DateTime 对象。

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // bool(false)
var_dump($date1 < $date2);  // bool(true)
var_dump($date1 > $date2);  // bool(false)

19
+1 DateTime 处理闰年和时区的问题,并且有一本不错的书可以放在书架上:http://www.phparch.com/books/phparchitects-guide-to-date-and-time-programming/ - hakre
3
有一种方法可以计算两个DateTime之间的总秒数吗?(不需要将时间组件相加) - potatoe
1
@Panique,$interval->days和$interval->d是不同的度量单位。你上面的评论是正确的,“显示总天数(不像上面分成年、月和日)”。 - jurka
3
注意,有一个错误会导致在某些 PHP 版本的 Windows 上,DateInterval 类型的 days 属性(始终为 6015)不正确:https://bugs.php.net/bug.php?id=51184 (参考其中的评论获取修复或解决方法)。 - Pim Schaaf
1
@AlejandroMoreno:然后$interval->invert将会是1。为什么不尝试一下,并且使用print_r($interval)打印出所有的属性,你就能看到了。 - Glavić
显示剩余14条评论

592
使用这个方法可以处理旧代码(PHP < 5.3;2009年6月)。要获取最新的解决方案,请参考jurka的上面的答案
你可以使用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);
编辑:显然,按照下面jurka所描述的方式是首选。如果你没有PHP 5.3或更高版本,那么我的代码通常只是建议使用。
评论中有几个人指出上面的代码只是一个近似值。我仍然相信,对于大多数情况来说,这是可以接受的,因为使用范围更多是为了提供时间的流逝或剩余的感觉,而不是提供精确度 - 如果你想要精确度,只需输出日期即可。
尽管如此,我决定解决这些抱怨。如果你真的需要一个精确的范围,但没有PHP 5.3的访问权限,请使用下面的代码(它应该在PHP 4中也能工作)。这是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)));

4
处理夏令时/冬令时并不是真的会影响到你。在这种特殊情况下,当你调整夏令时/冬令时时,一天等于23或25小时。 - Arno
4
同样的论点也可以用于闰年。它也没有考虑这一点。但是,我并不相信你真的想考虑这一点,因为我们讨论的是一个范围。范围的语义与绝对日期有些不同。 - Emil H
9
该函数存在错误。虽然适用于近似值,但在精确范围内是不正确的。首先,它假设一个月有30天,这意味着它将会把二月1日和三月1日之间的天数差异与七月1日到八月1日之间的天数差异视为相同(无论是否为闰年)。 - enobrev
1
在PHP中,引用变量位于函数签名中,而不是调用中。将所有的&移动到函数签名中。 - Paul Tarjan
1
虽然这是被接受的答案,但如果您使用的是PHP 5.3或更高版本,请查看此问题下面的以下答案:https://dev59.com/nnRB5IYBdhLWcg3wQVSV#3923228 - Parixit
显示剩余3条评论

88

最佳的做法是使用PHP的DateTime(以及DateInterval)对象。每个日期都封装在一个DateTime对象中,然后可以计算两者之间的差异:

$first_date = new DateTime("2012-11-30 17:03:30");
$second_date = new DateTime("2012-12-21 00:00:00");
DateTime对象将接受任何格式的strtotime()。如果需要更具体的日期格式,可以使用DateTime::createFromFormat()来创建DateTime对象。

在两个对象都被实例化后,您可以使用DateTime::diff()从一个对象中减去另一个对象。

$difference = $first_date->diff($second_date);

$difference 现在持有一个 DateInterval 对象,其中包含差异信息。使用 var_dump() 函数输出的结果如下:

object(DateInterval)
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 20
  public 'h' => int 6
  public 'i' => int 56
  public 's' => int 30
  public 'invert' => int 0
  public 'days' => int 20

为了格式化DateInterval对象,我们需要检查每个值并在其值为0时将其排除:
/**
 * Format an interval to show all existing components.
 * If the interval doesn't have a time component (years, months, etc)
 * That component won't be displayed.
 *
 * @param DateInterval $interval The interval
 *
 * @return string Formatted interval string.
 */
function format_interval(DateInterval $interval) {
    $result = "";
    if ($interval->y) { $result .= $interval->format("%y years "); }
    if ($interval->m) { $result .= $interval->format("%m months "); }
    if ($interval->d) { $result .= $interval->format("%d days "); }
    if ($interval->h) { $result .= $interval->format("%h hours "); }
    if ($interval->i) { $result .= $interval->format("%i minutes "); }
    if ($interval->s) { $result .= $interval->format("%s seconds "); }

    return $result;
}

现在只需要在 $difference DateInterval 对象上调用我们的函数即可:
echo format_interval($difference);

我们得到了正确的结果:

20天6小时56分钟30秒

实现目标所使用的完整代码:

/**
 * Format an interval to show all existing components.
 * If the interval doesn't have a time component (years, months, etc)
 * That component won't be displayed.
 *
 * @param DateInterval $interval The interval
 *
 * @return string Formatted interval string.
 */
function format_interval(DateInterval $interval) {
    $result = "";
    if ($interval->y) { $result .= $interval->format("%y years "); }
    if ($interval->m) { $result .= $interval->format("%m months "); }
    if ($interval->d) { $result .= $interval->format("%d days "); }
    if ($interval->h) { $result .= $interval->format("%h hours "); }
    if ($interval->i) { $result .= $interval->format("%i minutes "); }
    if ($interval->s) { $result .= $interval->format("%s seconds "); }

    return $result;
}

$first_date = new DateTime("2012-11-30 17:03:30");
$second_date = new DateTime("2012-12-21 00:00:00");

$difference = $first_date->diff($second_date);

echo format_interval($difference);

DateTime() 不是一个函数,而是一个对象,自 PHP 5.2 起就已经存在了。请确保您的服务器支持它。 - Madara's Ghost
2
@SecondRikudo DateTime::Diff 需要 PHP 5.3.0 - PhoneixS
因为 diff 给出了两个时间之间的差异。无论哪个日期更晚,差异都不为0。 - Madara's Ghost
1
这是一个非常好的答案,因为它提供了一个清晰的函数,可以在代码库中的任何地方调用,而不需要大量的时间计算。其他答案允许您在运行时丢弃回显计算,从而解决症状而不是解决问题...我添加的唯一元素(几乎所有其他帖子都没有涵盖)是如果超过1个,则对$interval元素进行复数处理。 - nickhar
我确实使用了这个方法,但是我遇到了一个大问题,如果你恰好有59天(30+29),那么它会变成“2个月”,因为它将第二个月计算为二月,这毫无意义,不知道该如何解决。 - Barbz_YHOOL
显示剩余2条评论

40

查看小时、分钟和秒...

$date1 = "2008-11-01 22:45:00"; 

$date2 = "2009-12-04 13:44:01"; 

$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));

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

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

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

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

9
可能这不会给出准确的结果。 - Dolphin
8
除非你被迫使用非常过时的 PHP 版本,否则它是一个糟糕的解决方案... - user895378
3
不那么D.R.Y.。比如,606024重复了15次。复制-粘贴重用万岁! - Peter Mortensen
1
闰年怎么办?一年的平均天数不是365天。 - Peter Mortensen
1
这段代码假设一个月平均有30天。即使假设一年有365天,一个平均月份为365/12=30.42天(约)。 - Peter Mortensen
显示剩余3条评论

21

看一下以下链接。这是我迄今为止找到的最好的答案.. :)

function dateDiff ($d1, $d2) {

    // Return the number of days between the two dates:    
    return round(abs(strtotime($d1) - strtotime($d2))/86400);

} // end function dateDiff
无论传入的日期参数哪一个更早或更晚都没有关系。该函数使用PHP ABS()绝对值函数,以始终返回正数作为两个日期之间天数的数量。
请注意,两个日期之间的天数不包括这两个日期。因此,如果你想要计算包括输入的日期在内的所有日期所代表的天数,你需要将该函数的结果加一(1)。
例如,上面的函数返回2013年02月09日和2013年02月14日之间的差异是5。但是,日期范围2013年02月09日至2013年02月14日期间的天数或日期数量是6。 http://www.bizinfosys.com/php/date-difference.html

1
问题要求的是年、月和日之间的差异,而不是总天数。 - Peter Mortensen
1
太棒了,这对我有用,可以得到天数差异,谢谢。 - Aman Deep

15
<?php
    $today = strtotime("2011-02-03 00:00:00");
    $myBirthDate = strtotime("1964-10-30 00:00:00");
    printf("Days since my birthday: ", ($today - $myBirthDate)/60/60/24);
?>

1
问题要求计算出差异的年数、月数和天数。但是这个输出结果是总天数。 - Peter Mortensen

14

我投票支持jurka答案,因为那是我最喜欢的,但我使用的是PHP 5.3以下版本...

我发现自己在解决类似的问题 - 这就是我首先来到这个问题的原因 - 但只需要计算小时数。但我的函数也很好地解决了这个问题,并且我没有自己的库来保存它,以防它会被遗忘和丢失,所以...希望这对某人有用。

/**
 *
 * @param DateTime $oDate1
 * @param DateTime $oDate2
 * @return array 
 */
function date_diff_array(DateTime $oDate1, DateTime $oDate2) {
    $aIntervals = array(
        'year'   => 0,
        'month'  => 0,
        'week'   => 0,
        'day'    => 0,
        'hour'   => 0,
        'minute' => 0,
        'second' => 0,
    );

    foreach($aIntervals as $sInterval => &$iInterval) {
        while($oDate1 <= $oDate2){ 
            $oDate1->modify('+1 ' . $sInterval);
            if ($oDate1 > $oDate2) {
                $oDate1->modify('-1 ' . $sInterval);
                break;
            } else {
                $iInterval++;
            }
        }
    }

    return $aIntervals;
}

测试代码:

$oDate = new DateTime();
$oDate->modify('+111402189 seconds');
var_dump($oDate);
var_dump(date_diff_array(new DateTime(), $oDate));

结果如下:

object(DateTime)[2]
  public 'date' => string '2014-04-29 18:52:51' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/New_York' (length=16)

array
  'year'   => int 3
  'month'  => int 6
  'week'   => int 1
  'day'    => int 4
  'hour'   => int 9
  'minute' => int 3
  'second' => int 8

我从这里得到了原始的想法,我对其进行了修改以适应我的需求(我希望我的修改也能显示在那个页面上)。

您可以很容易地通过从$aIntervals数组中删除不需要的间隔(例如“week”),或者可能添加$aExclude参数,或者在输出字符串时过滤它们来移除不需要的间隔。


很遗憾,由于年/月的溢出,这不能返回与DateInterval相同的内容。 - Stephen Harris
2
@StephenHarris:我还没有测试过这个,但是通过阅读代码,我非常有信心它应该会返回相同的结果——只要你删除$aIntervals中的week索引(因为DateDiff从不使用它)。 - Alix Axel
这是一个很好的解决方案,用于查找在两个日期之间每个时间间隔发生的日期。 - betweenbrain

12

我不知道你是否在使用PHP框架,但许多PHP框架都有日期/时间库和辅助程序,可以帮助您避免重新发明轮子。

例如CodeIgniter就有timespan()函数。只需输入两个Unix时间戳,它就会自动生成像这样的结果:

1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes

http://codeigniter.com/user_guide/helpers/date_helper.html


11

这里是可运行代码

$date1 = date_create('2007-03-24');
$date2 = date_create('2009-06-26');
$diff1 = date_diff($date1,$date2);
$daysdiff = $diff1->format("%R%a");
$daysdiff = abs($daysdiff);

10

使用此函数

//function Diff between Dates
//////////////////////////////////////////////////////////////////////
//PARA: Date Should In YYYY-MM-DD Format
//RESULT FORMAT:
// '%y Year %m Month %d Day %h Hours %i Minute %s Seconds' =>  1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// '%y Year %m Month %d Day'                       =>  1 Year 3 Month 14 Days
// '%m Month %d Day'                                     =>  3 Month 14 Day
// '%d Day %h Hours'                                   =>  14 Day 11 Hours
// '%d Day'                                                 =>  14 Days
// '%h Hours %i Minute %s Seconds'         =>  11 Hours 49 Minute 36 Seconds
// '%i Minute %s Seconds'                           =>  49 Minute 36 Seconds
// '%h Hours                                          =>  11 Hours
// '%a Days                                                =>  468 Days
//////////////////////////////////////////////////////////////////////
function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);

    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}

只需设置参数$differenceFormat,根据您的需要进行调整。

例如,我想要计算两年之间的差距,包括月份和日期,以此来计算你的年龄。

dateDifference(date('Y-m-d') , $date , '%y %m %d')

或者其他格式:

dateDifference(date('Y-m-d') , $date , '%y-%m-%d')


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接