函数名:date_interval_format()
适用版本:PHP 5 >= 5.3.0, PHP 7
用法:date_interval_format() 函数用于格式化时间间隔对象。
语法:string date_interval_format( DateInterval $interval, string $format )
参数:
- $interval:必需,一个 DateInterval 对象,表示时间间隔。
- $format:必需,指定返回时间间隔的格式化字符串。
返回值:返回格式化后的时间间隔字符串,如果参数无效或格式化失败则返回 false。
示例:
$date1 = new DateTime('2021-01-01');
$date2 = new DateTime('2021-02-28');
$interval = $date1->diff($date2);
// 格式化时间间隔
echo date_interval_format($interval, '%y 年 %m 月 %d 天');
// 输出:1 年 1 月 27 天
// 更详细的格式
echo date_interval_format($interval, '%y 年 %m 月 %d 天 %h 小时 %i 分钟 %s 秒');
// 输出:1 年 1 月 27 天 0 小时 0 分钟 0 秒
在上述示例中,我们首先创建了两个 DateTime 对象以表示开始日期和结束日期。然后,我们使用 DateTime 的 diff() 方法获取这两个日期之间的时间间隔,该方法返回一个 DateInterval 对象。最后,我们使用 date_interval_format() 函数将时间间隔对象格式化为指定的字符串。