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?

Upvotes: 3

Views: 18254

Answers (4)

jawira
jawira

Reputation: 4598

You have to create the interval with real dates:

<?php
$interval = date_diff(new DateTime, new DateTime('+1 year'));
echo $interval->format('%a'), PHP_EOL; // 365

Upvotes: 1

Gaby_64
Gaby_64

Reputation: 77

if you want something aware of the year or month context, use this, february will return 28 days, leap years will have their additional day

function interval2days($day, $interval) {
    $date = clone $day;
    $start = $date->getTimeStamp();
    $end = $date->add($interval)->getTimeStamp();
    return ($end-$start)/86400;
}

Upvotes: 0

Gergely Lukacsy
Gergely Lukacsy

Reputation: 3074

The problem is here:

$duration->format('%a');

As the manual says, "Total number of days as a result of a DateTime::diff() or (unknown) otherwise".

You need a valid dateInterval object returned by DateTime's diff() method to make the "a" parameter work with DateInterval::format() function:

$now = new DateTime(date('Y-m-d H:i:s'));
$duration = (new DateTime("+1 year"))->diff($now);
echo $duration->format('%a');

Looks like if the DateInterval object is not created by DateTime::diff(), it won't work. Hope it helps.

Upvotes: 8

Danial Aftab
Danial Aftab

Reputation: 139

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

Upvotes: 9

Related Questions