【问题标题】:PHP - Date / Time difference using only working hours [duplicate]PHP - 仅使用工作时间的日期/时间差异[重复]
【发布时间】:2013-02-19 13:38:52
【问题描述】:

我正在尝试创建一个函数来计算 2 次之间的时间差,但只包括工作时间。 这适用于跟踪完成工作所需时间的项目。

工作时间为周一至周五上午 9 点至下午 5 点。

  • 示例 1
    如果工作从下午 4:50 开始,并且有人在第二天上午 10 点查看该页面,则计时器将显示 1h 10m 0s。
  • 示例 2
    如果作业从下午 6:23 开始,并且有人在第二天上午 9:30 查看页面,则计时器将显示 30m 0s。
  • 示例 3
    如果工作在星期五下午 1:20 开始,并且有人在星期二下午 4 点查看页面,则计时器将显示 18h 40m 0s。 (不包括周六和周日!)

【问题讨论】:

  • 在本页查看答案link
  • @Peter 我尝试在 for 循环中每小时循环一次,并尝试使用 if 语句来缩小范围,但是当我进入分钟和秒时,它变得混乱和混乱。我现在真的有一个心理障碍,如果你能告诉我你会怎么做,我会非常感激。
  • @AmineMatmati 我看过了,这更侧重于跳过周末而不是工作时间以外的所有内容。
  • 你已经问过这个问题了:stackoverflow.com/questions/14937144/…

标签: php time timestamp datediff hour


【解决方案1】:

这可能有点压倒性,但在链接中@Amine Matmati 提供了您需要的所有工具。有了它,您可以轻松地浏览从开始时间戳到现在的每一天,并跳过周末和下班时间。

这有点笨拙,但它会工作。

strtotime(str, timestamp) 接受一个字符串,该字符串几乎是简单的英语命令,如果需要,还可以提供一个参考时间戳。这就是您从当前时间戳一直运行到结束时间戳的方式。

即。 strtotime('end of the working day', timestamp of when the job started);

[注意:'end of the day' 不是一个可接受的字符串,请查看底部的 PHP 手册链接,我只是想让你看看它对你有什么用处] em>

因此,如果您构建了一个从原始时间戳到现在的循环,您可以计算所走的工作小时数。

我会用伪代码向你展示逻辑:

$Present is present timestamp;
$Start is the starting timestamp;
$Hours will be the accumulated working hours between starting timestamp and present timestamp;

loop while present timestamp not reached {

if $Start does not occur on the same day as $Present{
  if $Start occurs inside of working hours {
    find the time to the end of the working day;
    add that time to $Hours;
  }

  find next day;
  if the next day is Saturday{
    update $Start to the working start of next Monday;
  }
  else{
    update $Start to the working start of the next day;
  }
}
else{
  find the time between $Start and $Present;
  add that time to $Hours;
  update $Start to $Present or Break;
  }
}

确实假设开始时间不会出现在周末,也不会出现在与当前时间戳同一天的工作时间之外(即之前),但控制这些时间非常简单的。

在这方面会成为你朋友的事情是:

@Amine Matmati 的链接:Time difference between 2 dates ignoring weekend time

PHP 日期():http://php.net/manual/en/function.date.php
PHP strtotime(): http://www.php.net/manual/en/function.strtotime.php

编码愉快!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    相关资源
    最近更新 更多