简体   繁体   中英

How to calculate time difference

$to = strtotime("2008-12-13 10:42:00");
$from = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
echo round(abs($to_time - $from_time) / 3600,2). " hours";

It is working good when I convert into minutes, but when converting into hours it's not giving the correct output.

Try This Source : http://php.net/manual/en/datetime.diff.php

<?php
$datetime1 = new DateTime('2008-12-13 10:42:00');
$datetime2 = new DateTime('2008-12-13 10:21:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%h hour');
echo $interval->format('%R%i minute');
?>

Use appropriate format from here http://php.net/manual/en/dateinterval.format.php

This should do it:

$from = new DateTime('2008-12-13 10:21:00');
$to = new DateTime('2008-12-13 10:42:00');

$diff = $to->diff($from);
$hours = $diff->h;//hours
$mins = $diff->i;//minutes
echo $hours.':'.$mins;

With the above the $diff is an array containing these keys:

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 0
    [i] => 21
    [s] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 1
    [days] => 0
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

I don't know what is the "correct output" that you are expecting.

21 minute
0.35 hours

The difference is 21 minutes, so 0.35h is correct.

Anyways your code is wrong, you are using $from_time and $to_time instead of $to and $from

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM