php种loop用法,使用PHP循环日期 (Loop through dates with PHP)

Here is part of a code I use, can probably be improved, depends on PHP version you use.

//usage

$Iterator=class Dates_DateIterator::factory('Daily',

new Datetime('20100227'),

new Datetime('20100324'));

foreach($Iterator as $i=>$day){

var_dump($i);

var_dump($day);

}

//code lib

abstract class Dates_DateIterator implements Iterator

{

/**

* Factory method, saves some code, also enable me to put everything in the same class

* as we use Autoload to load classes.

*/

static public function factory($cycle,DateTime $DateI,DateTime $DateII){

switch($cycle){

case 'Daily':

return new DaysIterator($DateI,$DateII);

case 'Weekly':

return new WeeksIterator($DateI,$DateII);

case 'Monthly':

return new MonthsIterator($DateI,$DateII);

case 'Yearly':

return new YearsIterator($DateI,$DateII);

default:

throw(new Exception('No valid cycle was chosen to iterate over'));

}

}

/**

* @var DateTime represents the start range.

*/

public $FromDate;

/**

* @var DateTime represents the end range.

*/

public $ToDate;

/**

* @var DateTime Current Date.

*/

protected $CurrentDate;

public function __construct(DateTime $DateI,DateTime $DateII)

{

if($DateII->format('U') > $DateI->format('U'))

{

$this->FromDate=$DateI;

$this->ToDate=$DateII;

$this->CurrentDate=$DateI;

}

else

{

$this->FromDate=$DateII;

$this->ToDate=$DateI;

$this->CurrentDate=$DateII;

}

}//EOF constructor

/**

* @return DateTime

*/

public function getClonedCurrent(){

return clone($this->CurrentDate);

}

public function current()

{

return $this->CurrentDate;

}//EOF current

public function currentDate()

{

return $this->CurrentDate->format('Ymd');

}//EOF current

public function rewind()

{

$this->CurrentDate=$this->FromDate;

}//EOF rewind

public function valid()

{

//Kill hours/minutes/seconds. If we are to add hours and minutes iterators, we will need to rethink this.

return (floor($this->CurrentDate->format('U')/(3600*24)) <= floor($this->ToDate->format('U')/(3600*24)));

}//EOF valid

}//EOF CLASS DateIterator

class DaysIterator extends SiTEL_Dates_DateIterator

{

public function __construct(DateTime $DateI,DateTime $DateII)

{

parent::__construct($DateI,$DateII);

}//EOF constructor

public function next()

{

$this->CurrentDate->modify('+1 day');

}//EOF next

public function key()

{

return $this->CurrentDate->format('d');

}//EOF key

}//EOD CLASS DaysIterator

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值