简体   繁体   中英

Days between two dates doesn't work in PHP

I need to compute the days between two dates (format YYYYMMDD)

I used two test dates, 2020-01-20 and 2020-02-20

$enddate = "20200220";
$startdate = "20200120";
$s = new DateTime($enddate);
$e = new DateTime($startdate);
$diff = $s->diff($e);
echo "days: ".$diff->d;

the result is 0 instead of being a month worth of days

days: 0

I understand that dates as strings might be ambiguous, so I also tried to specify the format, by doing:

$enddate = "20200220";
$startdate = "20200120";
$s = DateTime::createFromFormat('Ymd', $startdate);
$e = DateTime::createFromFormat('Ymd', $enddate);
$diff = $s->diff($e);
echo "days: ".$diff->d; 

Still got 0

days: 0

You can use strtotime

<?php

// strtotime converts any string date format to unix time

$date1 = "2020-01-20";
$date2 = "2020-02-20";

$seconds_in_a_day = 86400;


$diff = (strtotime($date2) - strtotime($date1))/$seconds_in_a_day;

echo $diff; // output 31
<?php 
    $enddate = "20200220";
    $startdate = "20200221";
    $date1 = new DateTime($enddate);
    $date2 = new DateTime($startdate); 
    echo $days  = $date2->diff($date1)->format('%a');
?>

The simple answer to your question is that, try above code, i had faced same problem in past and i have found below soultion for it.

Description: there is no need to put dashes in string date format, so there is no worry about your date format. I think the issue is with your return format, in my answer i used format %a which shows Total number of days between two days. you can view full list of formats here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM