Home Ask Login Register

Developers Planet

Your answer is one click away!

Chinmay Sarupria February 2016

Why PHP is returning wrong days between two dates?

There are a ton of such questions on Stackoverflow and before you mark this as duplicate, let me tell you that none of those work in my case.

Date Difference in php on days?

Calculate the difference between date/times in PHP

Dates difference with php

Finding the number of days between two dates

How to calculate the difference between two dates using PHP?

Above are the questions I have checked. The last question has an answer by Jurka which also unfortunately doesn't works. So here is my code:

$date1 = new DateTime(date('d-m-y'));
$date2 = new DateTime($etaDate);
$interval = $date1->diff($date2);
echo "difference " . $interval->days . " days ";

The $etaDate in above case is 03-02-16 and the current date is 08-02-16 so it should return 5 days but it returns a very high figure - 1826 days. I have tried different methods which also returns the same day figure.

A date value is stored as string in database so on retrieving I am again putting it back to date format using this code:

$newdate = DateTime::createFromFormat('d-m-y', $EntryDate);
$newdate->add(new DateInterval('P15D'));
$etaDate = $newdate->format('d-m-y');

$EntryDate is a variable that holds the date from the database, $etaDate converts it into date format.


Mr. Engineer February 2016

Just change the format of year from y to Y and it will work.

See the example : https://eval.in/514811

Vadivel S February 2016

Try This Code //YYYY-MM-DD format

$date1 = new DateTime(date('Y-m-d'));
$date2 = new DateTime($etaDate);
$interval = $date1->diff($date2);
echo "difference " . $interval->days . " days ";

Post Status

Asked in February 2016
Viewed 2,517 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life