diff($datetime_end)->days;"."/> diff($datetime_end)->days;".">

Home  >  Article  >  Backend Development  >  How to get the difference in days in php

How to get the difference in days in php

藏色散人
藏色散人Original
2022-01-11 10:26:363375browse

php method to get the number of days difference: 1. Convert the date into a timestamp, and then calculate the timestamp into a number of days; 2. Use the method in the date and time object to find the number of days difference between the two dates, code Such as "$datetime_start->diff($datetime_end)->days;".

How to get the difference in days in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How many days are needed to obtain php?

PHP The number of days difference between two dates

Find the number of days difference between two dates

Option 1: Convert the date to a timestamp, and then Timestamps are calculated as days. (Not recommended, just know that this happens)

<?php
$start_date = "2018-05-25";
$end_date = "2017-05-23";
 
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$days = abs(($start_time - $end_time) / 86400);
echo "时间差是:$days";
?>

Disadvantages: This method is not safe. ① The default type for converting dates into timestamps is int, and int space may not be enough. ② The timestamp value is too large, so use Not very scientific in calculation

Optimization and improvement,,,

Option 2: Use methods in date and time objects (recommended)

<?php
$start_date = "2018-05-25";
$end_date = "2017-05-23";
 
$datetime_start = new DateTime($start_date);
$datetime_end = new DateTime($end_date);
$days = $datetime_start->diff($datetime_end)->days;
echo "时间差是:$days";
?>

Recommended learning: "PHP Video tutorial

The above is the detailed content of How to get the difference in days in php. 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