Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's DateTime::Diff "steals" one day

Tags:

php

datetime

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");
like image 242
jureispro Avatar asked Dec 25 '22 01:12

jureispro


2 Answers

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 image 28
Jason Roman Avatar answered Jan 12 '23 11:01

Jason Roman


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

like image 169
Glavić Avatar answered Jan 12 '23 12:01

Glavić