从当前日期算起5天,并跳过周末

时间:2016-01-26 16:41:52

标签: php date

我有一个代码,它只是从当前日期开始增加5天。如何让它在周六和周日跳过?

date_default_timezone_set('Asia/Manila');
$current_date = date('Y-m-d');
$hearing = date('Y-m-d', strtotime("$current_date +5 days"));

1月27日星期三。在周末2月3日,周末将增加为期5天。我怎样才能做到这一点?谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您可以将$hearing传递给isWeekend(),直到它返回false(因为您知道这是工作日)

function isWeekend($date) {
    return (date('N', strtotime($date)) >= 6);
}

答案 1 :(得分:0)

您可以实现自己的Period Iterator。 根据您要添加的开始日期和天数,这将添加不包括周末的天数

<强>用法

    $startDateTime = new \DateTime('2017-01-27');
    // Will return 5 **business days** in the future.
    // Does not count the current day
    // This particular example will return 02-03-2017
    $endDateTime = addBusinessDays($startDateTime, 5);

功能

function addBusinessDays(\DateTime $startDateTime, $daysToAdd)
{
    $endDateTime = clone $startDateTime;
    $endDateTime->add(new \DateInterval('P' . $daysToAdd . 'D'));
    $period = new \DatePeriod(
        $startDateTime, new \DateInterval('P1D'), $endDateTime,
        // Exclude the start day
        \DatePeriod::EXCLUDE_START_DATE
    );

    $periodIterator = new PeriodIterator($period);
    $adjustedEndingDate = clone $startDateTime;
    while($periodIterator->valid()){
        $adjustedEndingDate = $periodIterator->current();
        // If we run into a weekend, extend our days
        if($periodIterator->isWeekend()){
            $periodIterator->extend();
        }
        $periodIterator->next();
    }

    return $adjustedEndingDate;
}

PeriodIterator类

class PeriodIterator implements \Iterator
{
    private $current;
    private $period = [];

    public function __construct(\DatePeriod $period) {
        $this->period = $period;
        $this->current = $this->period->getStartDate();
        if(!$period->include_start_date){
            $this->next();
        }

        $this->endDate = $this->period->getEndDate();
    }

    public function rewind() {
        $this->current->subtract($this->period->getDateInterval());
    }

    public function current() {
        return clone $this->current;
    }

    public function key() {
        return $this->current->diff($this->period->getStartDate());
    }

    public function next() {
        $this->current->add($this->period->getDateInterval());
    }

    public function valid() {
        return $this->current < $this->endDate;
    }

    public function extend()
    {
        $this->endDate->add($this->period->getDateInterval());
    }

    public function isSaturday()
    {
        return $this->current->format('N') == 6;
    }

    public function isSunday()
    {
        return $this->current->format('N') == 7;
    }

    public function isWeekend()
    {
        return ($this->isSunday() || $this->isSaturday());
    }
}