How to calculate the number of days between dates in PHP

墨辰丷
Release: 2023-03-27 17:08:01
Original
2875 people have browsed it

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;
Copy after login

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;);
?>
Copy after login

<?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;);
?>
Copy after login

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!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!