How to calculate the number of days difference between dates in php

PHPz
Release: 2024-04-09 15:39:01
Original
877 people have browsed it

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.

How to calculate the number of days difference between dates in php

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} 天";
?>
Copy after login

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} 天";
?>
Copy after login

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} 天";
?>
Copy after login

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!

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!