>我有一个代码,它只是简单地从当前日期开始添加 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日,星期三。在跳过周末的基础上增加 5 天将产生答案 2 月 3 日星期三。我该怎么做?谢谢你的帮助。
你可以$hearing
传递给isWeekend()
,直到它返回false
(因为你知道那是工作日)
function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
您可以实现自己的周期迭代器。给定开始日期和要添加的天数,这将添加不包括周末的天数
用法
$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;
}
周期迭代器类
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());
}
}