如何在php中计算周末周末

时间:2016-01-26 07:56:32

标签: php laravel-4

我有这样的约会

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

我的问题:

如何从$ start&中计算或计算周末? $结束日期范围.. ??

3 个答案:

答案 0 :(得分:1)

更现代的方法是使用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()而不是块数组[]

答案 1 :(得分:0)

这段代码可能会有所帮助:

<?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;
        }
    }

另一种解决方案可以是:(Get date range between two dates excluding weekends

答案 2 :(得分:0)

这可能有帮助:

$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>';