Hector Lamar
Hector Lamar

Reputation: 241

PHP 5.2.17 datetime difference

First before anyone writes it, I know there are many topics about it already and I have checked a lot of them somehow nothing works for me.

I have in mysql 2 datetime fields (date_in, date_out) I just need to subtract date in from date_out which is easy in php 5.3 but I am on someones server and cant update it... date in the both fields is formated like this (2014-06-02 16:43:47)

Example below works fine as it is (i found it somewhere on the Stack)

$start = new DateTime('2010-10-12');
$end = new DateTime();
$days = round(($end->format('U') - $start->format('U')) / (60*60*24));

BUT when I change $start and $end to my data from DB, last line $days throws out an error (the -> format('U')) seems to be a problem. How can this be fixed?

(difference between end/start will never be greater than hour at most)

Upvotes: 1

Views: 371

Answers (1)

Hector Lamar
Hector Lamar

Reputation: 241

I have figured it out finally!

$date_inA = $sql_array[3];
$date_inB = new DateTime($date_inA);
$date_outA = $sql_array[4];
$date_outB = new DateTime($date_outA);

$diff = round(($date_outB->format('U') - $date_inB->format('U')) / (60*60*24));

I needed to change string object value to datetime object, I thought it was already date time object in DB...

Upvotes: 1

Related Questions