douyao1856 2014-04-22 12:10
浏览 4
已采纳

PHP - 找出两次之间的差异

I'm trying to calculate the time difference (in hours) between two times inputted via a timepicker. I have working JavaScript code, but would rather use server side code to make this calculation as it's quite important. If you want me to post the working JS code let me know in comments.

Calculating the difference between the times is easy enough, but I require the output in a particular format. For example inputs of '07:30' and '14:00' would return 6.5 rather than 6.3. The reason for this is to make it easier for me to use this time difference in calculations.

PHP Code i've tried:

Attempt #1:

<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);

echo $time_diff->format('%h.%i');
?>

Returns 6.3 as expected.

Attempt #2:

<?php
$start_time = "07:30";
$end_time = "14:00";
$start_time = str_replace(":", "", $start_time);
$end_time = str_replace(":", "", $end_time);
$res = $end_time - $start_time;
$result = $res / 100;
echo $result;
?>

Returns 6.7.

Tool used to test output: http://codepad.viper-7.com/

  • 写回答

6条回答 默认 最新

  • dongzhanjuan5141 2014-04-22 12:15
    关注

    Just extract the minutes:

    <?php
    $start_time = new DateTime('07:30');
    $end_time = new DateTime('14:00');
    $time_diff = date_diff($start_time,$end_time);
    
    $hours = (int)$time_diff->format('%h');
    $hour_part =  ((int)$time_diff->format('%i')) / 60;
    echo $hours + $hour_part;
    ?>
    

    Make sure to change the type to (int) before any calculations.
    If you divide the minutes by 60 you will get what part of a hour they represent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类