i am batman
i am batman

Reputation: 669

PHP date difference error

$startDate = new DateTime("2016-06-01");
$endDate = new DateTime("2016-06-30");
$diff = date_diff($startDate,$endDate);
$differenceYear = $diff->format("%y");
$differenceMonth = $diff->format("%m");
$difference = $differenceYear*12 + $differenceMonth;
echo $difference;

Above code will output 0 as the result. But when I change those two dates to 2016-12-01 and 2016-12-31 the code gives 1 as the output. Why is that happening?

When I check this code online php editor it gives the right answer. But when I copied it to my local machine the answer shows wrong. Online editor has US/Pacific as the timezone. My pc has Asia/Kolkata timezone. Both has the same PHP version

Upvotes: 4

Views: 1057

Answers (2)

axiac
axiac

Reputation: 72177

Using my default timezone (Europe/Bucharest), a print_r($diff) produces:

DateInterval Object
(
    [m] => 1
    [d] => 0
    [days] => 30
)
# I removed the other components as they are irrelevant to the question
# and they are 0 anyway.

It means: "1 month and 0 days" (the m and d properties), 30 days in total (the days property).

Using Asia/Kolkata as the default time zone it prints:

DateInterval Object
(
    [m] => 0
    [d] => 30
    [days] => 30
)
# Again, all the other object properties are 0 and irrelevant for the question

This one means: "0 months and 30 days", 30 days in total.


As you can see, the total number of days (the days property) is the same (30) and correct.

Regarding the "1 month and 0 days" vs. "0 months and 30 days", both of them are correct and incorrect on the same time.

What's the definition of "one month"? It can be anything between 28 and 31 days. This means, "1 month and 0 days" is equal to "0 months and 28 days", "0 months and 29 days" a.s.o. on the same time.


The question title reads "PHP date difference error" -- there is no error in the PHP date difference. It is just a loose definition of the term "month" in the human languages and cultures.

Upvotes: 3

C3roe
C3roe

Reputation: 96151

This is a timezone issue. I’d recommend that you create your DateTime objects from date strings such as 2016-12-01 00:00:00 +00:00, so that you will always be working in UTC.

$startDate = new DateTime("2016-12-01  00:00:00 +00:00");
$endDate = new DateTime("2016-12-31  00:00:00 +00:00"); 
$diff = date_diff($startDate,$endDate);
$differenceYear = $diff->format("%y");
$differenceMonth = $diff->format("%m");
var_dump($differenceYear,$differenceMonth);
$difference = $differenceYear*12 + $differenceMonth;
echo $difference;

(Code taken from Xatenev’s comment, otherwise this answer looks so short ;-)

Upvotes: 1

Related Questions