Fatal error: Call to a member function difference() on string in error on tpl file I'm trying to calculate the value between two fields in my custom node.tpl file. I am trying to convert the code show on http://drupal.org/node/1364744, and I wrote the following one.

$birthday = format_date(strtotime($content['field_date_de_naissance']['#items'][0]['value']), 'custom', 'd/m/Y');
$today = date('m/d/Y');
$age = $birthday-&gt;difference($today,'years');
print $age;


I get this error.


  Fatal error: Call to a member function difference() on string in


What is wrong in my code?
The error is calling a method (difference()) on a string, while just PHP objects and classes implements methods. format_date() is documented to return a string, not a DateObject. 


  Return value
  
  A translated date string in the requested format.


The code I would use depends from what modules you have installed, and which PHP version you are using.


If you have the Date module installed, and you enabled the Date API module, I would use the following one.

$birthday = new DateObject($content['field_date_de_naissance']['#items'][0]['value']);
$age = $birthday-&gt;difference(date_now(), 'years');

If you don't have the Date module installed, but you have a recent version of PHP 5 (which means higher than 5.2.0), then I would use code similar to the following one.

$birthday = new DateTime($content['field_date_de_naissance']['#items'][0]['value']);
$age = $birthday-&gt;diff(new DateTime())-&gt;format('y');

If you are still using a PHP version lower than 5.2.0, or you just want code you can use without to worry about the PHP version, I would use the following code.

$birthday = strtotime($content['field_date_de_naissance']['#items'][0]['value']);
$age = format_interval(time() - $birthday, 1);


I am not using format_date() since it returns a translated string, which is not necessary to strtotime() (and probably, it would confuse it).
format_interval() consider a month made of 30 days; for this reason, the code shown above is probably giving a different value than the other methods.


Reference


DateTime::__construct()
DateTime::diff()
DateInterval::format()
format_date()
format_interval()