Home > php教程 > php手册 > PHP中如何计算日期的间隔天数

PHP中如何计算日期的间隔天数

WBOY
Release: 2018-09-27 17:39:07
Original
1235 people have browsed it

刚开始在没有查PHP手册的情况下,用比较老套方法也折腾出来了,代码是这样子实现的:

    $date_1 = date('Y-m-d');
    $date_2= '2012-07-16';
    $date1_arr = explode("-",$date_1);
    $date2_arr = explode("-",$date_2);
    $day1 = mktime(0,0,0,$date1_arr[1],$date1_arr[2],$date1_arr[0]);
    $day2 = mktime(0,0,0,$date2_arr[1],$date2_arr[2],$date2_arr[0]);
    $days = round(($day2 - $day1)/3600/24);
    echo $days; exit;
Copy after login

后来google了一下  。发现PHP手册里 有个 DATE_DIFF 的方法 ,就是实例化了datetime 的这个类,调用diff这个方法:PHP版本>= 5.3 有效

<?php
$datetime1 = new DateTime(&#39;2009-10-11&#39;);
$datetime2 = new DateTime(&#39;2009-10-13&#39;);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

<?php
$datetime1 = date_create(&#39;2009-10-11&#39;);
$datetime2 = date_create(&#39;2009-10-13&#39;);
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>
Copy after login

这两种方法都可以实现。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template