Search code examples
phpdrupal-7

Calculating date difference


I'm calculating the age of a user by subtracting his age from today's date. The problem I have is that it show their age as whole number. But rather than showing it as a whole number, I'd like to display it as decimal like 25.5 or 27.3. I tried using round and number_format but neither worked.

$bday = $data->_field_data['node_field_data_field_game_players_nid']['entity']->field_player_birthday['und'][0]['value'];
$now = date("Y/m/d");
$diff = ($now) - date($bday);
echo number_format(round($diff, 2), 2); 

Solution

  • you can try this:

    $bday = $data->_field_data['node_field_data_field_game_players_nid']['entity']->field_player_birthday['und'][0]['value'];
    echo  number_format(round((strtotime(date('Y-m-d')) - strtotime($bday))/(60*60*24*365),2),2);
    

    However, above calculation is very rough. if you want get value more precisely you should use date_diff for that:

    $bday = $data->_field_data['node_field_data_field_game_players_nid']['entity']->field_player_birthday['und'][0]['value'];
    $date1=date_create($bday); //create date object
    $date2=date_create(date("Y-m-d")); //create date object
    $curyearmaxdays=date("z", mktime(23,59,59,12,31,date("y")))+1; //count of days in the current year
    $diff = date_diff($date1, $date2); //difference between two date objects
    $realdiff=$diff->y + $diff->m/12+$diff->d/$curyearmaxdays;
    echo  number_format(round($realdiff,2),2);