I want to calculate date difference between two days. Problem is that when I calculate days one day (current day) is missing from calculation.
Lets say that date1 is 20-12-2014 and date2 is 21-12-2014. Results of DateTime::Diff using these two dates are 0 (I want to be 1, not zero)
Did I miss something bad or DateTime::Diff calculates date difference like i explained above?
Here is code that I am using (I want to display date difference in days):
$currentDay = new DateTime();
$listDay = new DateTime($results["date"]);//from mysql database (output is like 21-12-2014
$interval = $currentDay->diff($listDay);
$daysLeft=(int)$interval->format("%r%a");
You should make very sure you're passing in 2 different dates because if you make 2 new DateTime objects that are 1 day apart, it will give you a difference of 1 day. Also, you can shorten your last two lines to just one:
$daysLeft = $currentDay->diff($listDay)->days;
Like @Matt already said in the comment, you are not only comparing dates, but dates with times, where in $currentDay
variable you have time set to current time, and time in $listDay
is set to 00:00:00
. You can quickly see that if you dump those 2 variables, like print_r($currentDay);
and print_r($listDay);
.
Solution would be, to create $currentDay
DateTime object with time set to 00:00:00
, and this can easily accomplished with today
keyword:
$currentDay = new DateTime('today');
$listDay = new DateTime($results['date']);
$interval = $currentDay->diff($listDay);
echo $interval->format('%r%a');
demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With