phpdateinterval

How to retrieve the number of days from a PHP date interval?


I am trying to retrieve the number of days for a PHP interval. When I run the following piece of code on http://sandbox.onlinephpfunctions.com/:

$duration = new \DateInterval('P1Y');
echo $duration->format('%a');
echo "Done";

I get:

(unknown)Done

What am I doing wrong?


Solution

  • The '%a' will return the number of days only when you take a time difference otherwise it will return unknown.
    You can use '%d' to get the days but it will also return 0 in the case of new \DateInterval('P1Y') as it does not convert years to days.
    One easy way to get the number of days is to create a DateTime at zero time, add the interval to it, and then get the resulting timestamp:

    <?php
    $duration = new \DateInterval('P1Y');
    $intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($duration)->getTimeStamp();
    $intervalInDays = $intervalInSeconds/86400; 
    echo $intervalInDays;
    echo " Done";