How to get difference between two Dates in Symfony MongoDB?

ABS picture ABS · Aug 14, 2013 · Viewed 7.9k times · Source

I have a problem with calculate dates difference between a PHP date object and current time.I know that i must get current time with this:

//in a symfony controller
new \DateTime("now")

and i have a Member Document(entity in MySql) that has a field like this :

class Member {
    //some fields

    /**
     * @ODM\Date
     */
    protected $regDate;

    //and so on
}

Now i want to calculate user activity :

// $member declared and assigned
$activity = new \DateTime("now") - $member->getRegDate();

But this error occurs:

Object of class DateTime could not be converted to int

What mistake i do?Thanks for any help

Answer

Derick picture Derick · Aug 14, 2013

You can use date_diff to calculate the difference:

$diff = date_diff(new DateTime(), $member->getRegDate());
var_dump( $diff ); // « shows some properties.

For more information, see the documentation on date_diff and DateInterval.

BTW, you don't need to use "now" either, as that is the default behaviour.