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.
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');
use the date() function.
$time_diff = $expiry_time - $current_date;
echo date('H:i:s', $time_diff);
http://php.net/manual/fr/function.date-diff.php has a bunch of useful stuf to do this operation as well
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);