Home > Article > Backend Development > How to calculate the number of days between dates in PHP
This article mainly introduces the method of calculating the number of days between dates in PHP programming, involving the conversion and calculation of date and time in PHP. Friends who need it can refer to it.
I didn’t check the PHP manual at the beginning. In this case, I also tried to use a relatively old-fashioned method. The code is implemented like this:
$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;
Later I googled it. I found that there is a DATE_DIFF method in the PHP manual, which instantiates the datetime class and calls the diff method: PHP version >= 5.3 valid
<?php $datetime1 = new DateTime('2009-10-11'); $datetime2 = new DateTime('2009-10-13'); $interval = $datetime1->diff($datetime2); echo $interval->format('%R%a days'); ?>
<?php $datetime1 = date_create('2009-10-11'); $datetime2 = date_create('2009-10-13'); $interval = date_diff($datetime1, $datetime2); echo $interval->format('%R%a days'); ?>
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
PHPQuoted calling method analysis_php skills
PHP Analysis of the difference between addslashes and mysql_escape_string_php skills
php The submitted data is generated as a txt file_php Skill
The above is the detailed content of How to calculate the number of days between dates in PHP. For more information, please follow other related articles on the PHP Chinese website!