在 PHP 中减去时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5463549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subtract time in PHP
提问by PsychoX
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?
我正在写一个简单的script
. 用户设置他们的工作开始和结束时间。例如,有人从 8:00 到 16:00 工作。我怎样才能减去这个时间来看看这个人工作了多长时间?
I was experimenting with strtotime();
but without success...
我正在尝试strtotime();
但没有成功......
回答by fab
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.
这会给你带来小时的差异。
回答by jm_toball
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.
这将为您提供一个人工作的时间。
回答by Developer Rakesh
Another solution would be to go through the Unix-timestamp integer value difference (in seconds).
另一种解决方案是通过 Unix-timestamp 整数值差异(以秒为单位)。
<?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.
如果您的原始日期以 Unix 时间戳格式存储,则此解决方案会更好。