给定两个日期,在PHP中找到工作日数的最佳方法是什么?

时间:2020-03-05 18:58:05  来源:igfitidea点击:

标题几乎是不言自明的。给定两个日期,使用PHP查找工作日数的最佳方法是什么?工作日为星期一至星期五。

例如,我如何确定在" 31/08/2008"和" 13/09/2008"之间有10个工作日?

解决方案

回答

一种方法是使用strtotime(...)将日期转换为unix时间戳,减去结果并用86400(24 * 60 * 60)进行除法:

$dif_in_seconds = abs(strtotime($a) - strtotime($b));
$daysbetween = $dif_in_seconds / 86400;

ETA:哦。意思是像周一至周五那样的工作日。

回答

最好的方法是遍历给定日期范围内的所有日期,并获取每个日期的星期几。如果是工作日,则增加一个计数器。在该过程结束时,我们将获得工作日数。

PHP函数mktime()和date()(用于UNIX时间戳)是朋友。

回答

$datefrom = strtotime($datefrom, 0);
        $dateto = strtotime($dateto, 0);

        $difference = $dateto - $datefrom;

        $days_difference = floor($difference / 86400);
        $weeks_difference = floor($days_difference / 7); // Complete weeks

        $first_day = date("w", $datefrom);
        $days_remainder = floor($days_difference % 7);

        $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
        if ($odd_days > 7) { // Sunday
            $days_remainder--;
        }
        if ($odd_days > 6) { // Saturday
            $days_remainder--;
        }

        $datediff = ($weeks_difference * 5) + $days_remainder;

从这里:http://www.addedbytes.com/php/php-datediff-function/

回答

如果要创建发票系统,则必须考虑银行假期,复活节等。计算起来并不容易。

我所见过的最好的办法是用预生成天表及其类型的SQL数据库,然后(每天每一年= 365排排)进行简单的计数查询与正确选择(WHERE子句)。

我们可以在Joe Celko的《集合中的思维:SQL中的辅助,时间和虚拟表》中找到完整描述的解决方案