get time difference in hours minutes and seconds

南笙酒味 提交于 2019-12-25 02:26:33

问题


I have two dates,

$expiry_time = strtotime('comming from database');
$current_date = strtotime(date('Y-m-d H:i:s'));
$time_diff = ($expiry_time-$current_date)/(3600);

Here, $time_diff will give me difference in hours. eg. 5.67. But, I want it in hours, minute and second format. How can I achieve this? Thanks.


回答1:


Use DateTime() with DateInterval()

$expiry_time = new DateTime($row['fromdb']);
$current_date = new DateTime();
$diff = $expiry_time->diff($current_time);
echo $diff->format('%H:%I:%S');



回答2:


use the date() function.

$time_diff = $expiry_time - $current_date;
echo date('H:i:s', $time_diff);



回答3:


http://php.net/manual/fr/function.date-diff.php has a bunch of useful stuf to do this operation as well




回答4:


You should use the DateTime class but if you use PHP version older than 5.2 you can do it like that:

function convert_time_by_seconds($interval) {
    if($interval < 0) {
        return false;
    }
    $seconds_n_miliseconds = explode('.', $interval);
    $interval = $seconds_n_miliseconds[0];

    $hours = floor($interval / (60*60));
    $minutes = floor(($interval - ($hours*60*60)) / 60);
    $seconds = floor(($interval - ($hours*60*60)) - ($minutes*60));
    $ms = empty($seconds_n_miliseconds[1]) ? 0 : $seconds_n_miliseconds[1];
    return array('h' => $hours, 'm' => $minutes, 's' => $seconds, 'ms' => $ms);
}

$time_diff = time() - strtotime('2014-07-17 14:23:51');
$result = convert_time_by_seconds($time_diff);
var_dump($result);


来源:https://stackoverflow.com/questions/24936855/get-time-difference-in-hours-minutes-and-seconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!