Home > Backend Development > PHP Tutorial > php gets the number of days between dates

php gets the number of days between dates

WBOY
Release: 2024-04-09 13:24:01
Original
777 people have browsed it

Question: How to calculate the number of days between two dates in PHP? Answer: Create two DateTime objects; use the diff() method to calculate the days interval; output the result.

php gets the number of days between dates

PHP Gets the number of days between dates

In PHP, we can use the datediff() function to Calculate the number of days between two dates.

<?php

// 创建两个日期对象
$date1 = new DateTime('2023-01-01');
$date2 = new DateTime('2023-01-10');

// 计算日期间隔天数
$interval = $date1->diff($date2);

// 输出天数间隔
echo $interval->days;
?>
Copy after login

Practical Case

Suppose we have a database that stores the user's order date. We need to calculate the number of days between the user's first order and the last order.

<?php

// 连接数据库并查询订单数据
$mysqli = new mysqli("localhost", "root", "password", "database");
$sql = "SELECT MIN(order_date) AS first_order, MAX(order_date) AS last_order FROM orders WHERE user_id = 1";
$result = $mysqli->query($sql);

// 获取订单日期范围
$row = $result->fetch_assoc();
$first_order = $row['first_order'];
$last_order = $row['last_order'];

// 创建日期对象并计算天数间隔
$date1 = new DateTime($first_order);
$date2 = new DateTime($last_order);
$interval = $date1->diff($date2);

// 输出天数间隔
echo $interval->days;
?>
Copy after login

The above is the detailed content of php gets the number of days between dates. 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