date_diff()

1. 定义

该函数为对象DateTime的方法diff()的别名。该函数返回两个DateTime对象之间的时间间隔信息。

2. 语法

public DateTime::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval public DateTimeImmutable::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval public DateTimeInterface::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval

date_diff ( DateTimeInterface $datetime1 , DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval

3. 参数说明

参数 可选性 数据类型 描述
$datetime1 必需 DateTimeInterface DateTimeInterface时间对象
$datetime2 必需 DateTimeInterface DateTimeInterface时间对象
$absolute 可选 布尔值 是否强制转换间隔为正值

4. 示例

<?php

// date_diff()
// 返回两个`DateTime`对象之间的时间间隔信息

// 面向对象式
$time1 = new DateTime('2019-08-31');
$time2 = new DateTime('2019-09-01');
$diff = $time1->diff($time2);
var_dump($diff);
/* 输出:
object(DateInterval)#3 (16) {
    ["y"]=>int(0)
    ["m"]=>int(0)
    ["d"]=>int(1)
    ["h"]=>int(0)
    ["i"]=>int(0)
    ["s"]=>int(0)
    ["f"]=>float(0)
    ["weekday"]=>int(0)
    ["weekday_behavior"]=>int(0)
    ["first_last_day_of"]=>int(0)
    ["invert"]=>int(0)
    ["days"]=>int(1)
    ["special_type"]=>int(0)
    ["special_amount"]=>int(0)
    ["have_weekday_relative"]=>int(0)
    ["have_special_relative"]=>int(0)
  }
 */

// 面向过程式
$time1 = date_create('2019-08-31');
$time2 = date_create('2019-09-01');
$diff = date_diff($time1, $time2);
var_dump($diff);
/* 输出:
object(DateInterval)#3 (16) {
    ["y"]=>int(0)
    ["m"]=>int(0)
    ["d"]=>int(1)
    ["h"]=>int(0)
    ["i"]=>int(0)
    ["s"]=>int(0)
    ["f"]=>float(0)
    ["weekday"]=>int(0)
    ["weekday_behavior"]=>int(0)
    ["first_last_day_of"]=>int(0)
    ["invert"]=>int(0)
    ["days"]=>int(1)
    ["special_type"]=>int(0)
    ["special_amount"]=>int(0)
    ["have_weekday_relative"]=>int(0)
    ["have_special_relative"]=>int(0)
  }
 */
echo '两个日期之间间隔了 ', $diff->format('%a'), ' 天';
// 输出:两个日期之间间隔了 1 天

5. 延展阅读

  • date_add():对一个DateTime对象增加一定量的年、月、日、时、分、秒等时间间隔
  • date_sub():对指定DateTime对象减少一定量的年、月、日、时、分、秒等时间间隔