我正在通过从今天的日期中减去其年龄来计算用户的年龄。我的问题是,它显示了他们的年龄整数。但是,我不想将其显示为整数,而是将其显示为小数,例如25.5或27.3。我尝试使用round和number_format,但都没有用。
$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);
答案 0 :(得分:0)
您可以尝试以下操作:
$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);
但是,以上计算非常粗糙。如果您想更精确地获取价值,则应使用date_diff来实现:
$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);