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

php gets the number of days between dates

WBOY
WBOYOriginal
2024-04-09 13:24:01755browse

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;
?>

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;
?>

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!

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