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

Jérôme Verstrynge picture Jérôme Verstrynge · Feb 20, 2017 · Viewed 10.7k times · Source

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?

Answer

Danial Aftab picture Danial Aftab · Feb 20, 2017

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