【问题标题】:Calculate total hours, best solution?计算总小时数,最佳解决方案?
【发布时间】:2013-04-09 14:59:38
【问题描述】:

我正在制作一个包含条目的表格,其中包含签入、结帐和描述。 checkin 和 checkout 都是日期时间字段。

我想计算一个项目的总工作时间。 这是我在 1 次结帐和一次签入之间的计算:

{? $checkin = new DateTime($hour->checkin) ?}
{? $checkout = new DateTime($hour->checkout) ?}
@if($hour->checkout == '0000-00-00 00:00:00')
    {? $checkout = new DateTime() ?}
@endif
{? $diff = $checkout->diff($checkin) ?}
{? $hours = $diff->format('%H:%I') ?}

现在,我计算总秒数:

$totaltime += strtotime("January 1, 1970 " . $hours . ":00")

然后在显示所有内容后,我通过以下方式计算 HOURS 的数量:

public static function format_time($seconds,$separator=':', $format = "%02d%s%02d") // t = seconds, f = separator 
    {
        return sprintf($format, floor($seconds/3600), $separator, ($seconds/60)%60, $separator, $seconds%60);
    }

然而,当我这样做时:-

strtotime("January 1, 1970 00:40:00")

我得到一个负整数。我做错了什么?

【问题讨论】:

  • 当您真正感兴趣的是时差时使用 unix 时间戳是一个非常糟糕的主意。以分钟为单位计算个体差异,将这些分钟相加,然后将它们格式化为 hh:mm。 (同样,不使用基于 unis 时间戳的日期函数,而是使用简单的数学运算。)
  • 另外,请确保以 UTC(或 GMT)获取这些时间。例如gmdate() 函数。否则,您可能会在夏令时转换时得到不正确或奇怪的结果。
  • @MattJohnson 我的时区设置为欧洲/阿姆斯特丹,这会影响它吗?
  • 是的。 Reference here。示例 - 如果您使用当地时间并且您的 checkin"2013-10-27 00:00:00" 并且您的 checkout"2013-10-27 04:00:00" 您会认为这将是 4 小时,但实际上它会是 5 小时。如果其中任何一个时间是 @ 987654331@ 你不知道该怎么做,因为它可以指转换之前或之后。

标签: php datetime


【解决方案1】:
<?php
$checkin[0] = "2013-03-09 10:00:01";
$checkout[0] = "2013-03-12 10:55:15";

$checkin[1] = "2013-03-15 10:00:01";
$checkout[1] = "2013-03-15 10:55:15";

$checkin[2] = "2013-04-09 10:00:01";
$checkout[2] = "2013-04-15 10:55:15";

$diffSeconds = 0;
for($i = 0; $i < count($checkin)-1; $i++){
  $diffSeconds += strtotime($checkout[$i]) - strtotime($checkin[$i]);
}
$hours = floor($diffSeconds/3600);
echo $hours.' hours';
?>

【讨论】:

  • 这是关于整个工作时间的,所以有更多条目。所有小时和分钟的总和。
猜你喜欢
  • 2016-11-14
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 2023-03-13
  • 2014-09-18
  • 1970-01-01
相关资源
最近更新 更多