Subtract time in PHP

假如想象 提交于 2020-01-09 02:30:05

问题


I have been looking for an answer for a few hours now, but I can't find one.

I'm writing a simple script. The user sets their work start and end time. So, for example, somebody is working from 8:00 to 16:00. How can I subtract this time to see how long the person has been working?

I was experimenting with strtotime(); but without success...


回答1:


A bit nicer is the following:


$a = new DateTime('08:00');
$b = new DateTime('16:00');
$interval = $a->diff($b);

echo $interval->format("%H");

That will give you the difference in hours.




回答2:


If you get valid date strings, you can use this:

$workingHours = (strtotime($end) - strtotime($start)) / 3600;

This will give you the hours a person has been working.




回答3:


Another solution would be to go through the Unix-timestamp integer value difference (in seconds).

<?php
    $start = strtotime('10-09-2019 12:01:00');
      $end = strtotime('12-09-2019 13:16:00');

      $hours = intval(($end - $start)/3600);
      echo $hours.' hours'; //in hours

      //If you want it in minutes, you can divide the difference by 60 instead
      $mins = (int)(($end - $start) / 60);
      echo $mins.' minutues'.'<br>';
?>

This solution would be a better one if your original dates are stored in Unix-timestamp format.



来源:https://stackoverflow.com/questions/5463549/subtract-time-in-php

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