Home >Backend Development >PHP Tutorial >How to calculate the number of days between dates in PHP

How to calculate the number of days between dates in PHP

墨辰丷
墨辰丷Original
2018-05-23 14:54:522981browse

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

<?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(&#39;%R%a days&#39;);
?>

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!

Statement:
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