如何用 php 计算日期周末


How can I calculate date weekend in php

我有这样的约会

    $start = strtotime('2010-01-01'); $end = strtotime('2010-01-25');

我的问题:

如何从$start和$end日期范围内计算或计算周末..??

一种更现代的方法是使用 php 的 DateTime 类。 下面,你得到一个以周数作为键的数组。我添加了周数和周末天数。

<?php
$begin = new DateTime('2010-01-01');
$end = new DateTime('2010-01-25');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);
$weekends = [];
foreach($daterange as $date) {
    if (in_array($date->format('N'), [6,7])) {
        $weekends[$date->format('W')][] = $date->format('Y-m-d');
    }
}
print_r($weekends);
echo 'Number of weeks: ' . count($weekends);
echo 'Number of weekend days: ' . (count($weekends, COUNT_RECURSIVE) - count($weekends));

注意:如果您使用的是 PHP 5.3,请使用 array() 而不是块数组[]

也许这个代码片段会有所帮助:

<?php
    //get current month for example
    $beginday = date("Y-m-01");
    $lastday  = date("Y-m-t");
    $nr_work_days = getWorkingDays($beginday, $lastday);
    echo $nr_work_days;
    function getWorkingDays($startDate, $endDate)
    {
        $begin = strtotime($startDate);
        $end   = strtotime($endDate);
        if ($begin > $end) {
            echo "startdate is in the future! <br />";
            return 0;
        } else {
            $no_days  = 0;
            $weekends = 0;
            while ($begin <= $end) {
                $no_days++; // no of days in the given interval
                $what_day = date("N", $begin);
                if ($what_day > 5) { // 6 and 7 are weekend days
                    $weekends++;
                };
                $begin += 86400; // +1 day
            };
            $working_days = $no_days - $weekends;
            return $working_days;
        }
    }

另一种解决方案可以是:(获取两个日期之间的日期范围,不包括周末)

这可能会有所帮助:

$start = strtotime('2010-01-01'); 
$end = strtotime('2010-01-25');
$differ = $end-$start;
$min = $differ/60;
$hrs = $min/60;
$days = $hrs/24;
$weeks = $days/7;

if(is_int($weeks))
$weeks++;
echo '<pre>';
print_r(ceil($weeks));
echo '</pre>';