Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does DateTime::diff return 0 days between these dates?

Tags:

php

datetime

Consider the following test case:

$start = new DateTime("2011-02-25");
$end = new DateTime("2011-03-25");

$interval = $end->diff($start);


echo "INTERVAL = ".$interval->format("%d");  // Should give me the 
                                             // interval in days, right?
echo "START = ".$start->format("Y-m-d");
echo "END = ".$end->format("Y-m-d");

The result is:

INTERVAL = 0  <---------- WTF????
START = 2011-02-25
END = 2011-03-25

diff() seems to claim that the period between February 25th, 2011 and March 25, 2011 is 0 days!

I must be overlooking something. But what?

like image 629
Pekka Avatar asked May 03 '26 04:05

Pekka


1 Answers

you need to use format code 'a'. d is the number of days in the diff, not the net number of days. in the dateinterval object, days is the corresponding field. in your example, you will see m = 1

like image 172
Foo Bah Avatar answered May 05 '26 17:05

Foo Bah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!