计算日期差异
Calculating date difference
我通过从今天的日期减去他的年龄来计算用户的年龄。我的问题是它将他们的年龄显示为整数。但我不想将其显示为整数,而是将其显示为小数,如 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);
你可以试试这个:
$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);
我通过从今天的日期减去他的年龄来计算用户的年龄。我的问题是它将他们的年龄显示为整数。但我不想将其显示为整数,而是将其显示为小数,如 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);
你可以试试这个:
$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);