There are two ways to calculate date differences in PHP: 1. Using the DateInterval class, 2. Using the strtotime and date_diff functions. The specific implementation methods are: 1. Use the diff method to obtain the difference between two dates in the DateInterval object, and then obtain the difference in days; 2. Convert the date into a timestamp, use the date_diff function to obtain the date difference, and then convert the difference in days into an integer.
PHP How to calculate the number of days difference between dates
In PHP, there are two common methods to calculate two dates The difference in days between:
Method 1: DateInterval
<?php // 日期1 $date1 = new DateTime('2023-03-08'); // 日期2 $date2 = new DateTime('2023-03-15'); // 计算日期差 $interval = $date1->diff($date2); // 获取天数差 $daysDiff = $interval->days; // 输出天数差 echo "日期差:{$daysDiff} 天"; ?>
Method 2: strtotime and date_diff
<?php // 日期1 $date1 = strtotime('2023-03-08'); // 日期2 $date2 = strtotime('2023-03-15'); // 计算日期差 $daysDiff = (int) (($date2 - $date1) / 86400); // 输出天数差 echo "日期差:{$daysDiff} 天"; ?>
actualcase
Suppose you have a student's attendance record, which contains the enrollment date and withdrawal date. You want to know how many days a student spent in school.
<?php // 获取入学日期和退学日期 $enrollmentDate = strtotime('2021-08-16'); $leaveDate = strtotime('2023-05-18'); // 使用strtotime和date_diff计算天数差 $daysDiff = (int) (($leaveDate - $enrollmentDate) / 86400); // 输出学生在学校呆了的天数 echo "学生在学校呆了:{$daysDiff} 天"; ?>
The above is the detailed content of How to calculate the number of days difference between dates in php. For more information, please follow other related articles on the PHP Chinese website!