Php date-> diff () returns meaningless sums

This is my code:

$logdate = Input::get('logdate');
            $enddate = Input::get('enddate');
            //Cast the dates to yyyy-dd-mm format for comparison
            $startdt  = date('Y-d-m',strtotime($logdate));
            $enddt = date('Y-d-m',strtotime($enddate));
            //Cast the dates into datetime objects
            $date1 = new DateTime($startdt);
            $date2 = new DateTime($enddt);
            //Calculate the difference between the 2 datetime objects
            $diff = $date1->diff($date2, true);
            //cast logdate into correct format for entry in the database
            $newlogdate = strtotime($logdate);
            $formatlogdate = date('Y-d-m',$newlogdate);

      

I use this to get the number of days in an interval:

 Log::info(intval($diff->days));

      

The code here works great when I write code that includes 12 day differences or less with the same month, but as soon as it is more than 12 days or as soon as I try to calculate the difference between 2 months it goes away and will give me 16000+ as a result

For example, according to this code, the difference in days between 26/04/2015 and 02/05/2015 is 16557 days, I don’t know how they get to that number, but it’s about 45 years old and the result is always 16000+ regardless of of what dates I choose if they are outside the 12 day radius of the month

+3


source to share


3 answers


When you do - date('Y-d-m',strtotime($logdate));

, it returns - 1970-01-01

for both dates. /

creates a problem. Try it -

$log = '26/04/2015';
$end = '02/05/2015';

$date1 = new DateTime(str_replace('/', '-', $log));
$date2 = new DateTime(str_replace('/', '-', $end));
$diff = $date1->diff($date2, true);
echo $diff->days;

      



Output

6

      

+2


source


The correct way to do it would be: -

$log = '26/04/2015';
$end = '02/05/2015';

$date1 = \DateTime::createFromFormat('d/m/Y', $log);
$date2 = \DateTime::createFromFormat('d/m/Y', $end);
$diff = $date1->diff($date2, true);
echo $diff->days;

      



http://3v4l.org/EhGaA

0


source


Or try:

$datetime1 = strtotime("2011-10-10 10:00:00");
$datetime2 = strtotime("2011-10-10 10:45:00");
$interval  = abs($datetime2 - $datetime1);
$minutes   = round($interval / 60);
echo 'Diff. in minutes is: '.$minutes; 

      

0


source







All Articles