PHP5 Date Iterator

December 10th, 2009

I’ve recently had cause to iterate through ranges of dates, either Weekly, Monthly or Daily and for some reason there isn’t really a good default way to do this. So I wrote my own. This is a pretty basic implementation of an iterator but it serves its without too much fuss.


class Date_Iterator implements Iterator {
	private $increment;
	private $startDate;
	private $endDate;

	private $currentDate;

	private $iterations = 0;

	/**
	 *
	 * @param string $increment Anything that strtotime can understand. eg. day, week, month, year
	 * @param int|string $startDate
	 * @param int|string $endDate
	 * @return
	 */
	function __construct($increment, $startDate, $endDate) {
		$this->increment = $increment;

		if(is_int($startDate)) {
			$this->startDate = $startDate;
		} else {
			$this->startDate = strtotime($startDate);
		}

		if(is_int($endDate)) {
			$this->endDate = $endDate;
		} else {
			$this->endDate = strtotime($endDate);
		}
		$this->currentDate = $this->startDate;
	}

	function current() {
		return date("d-M-Y", $this->currentDate);
	}

	function next() {
		$current = date("d-M-Y", $this->currentDate);
		$this->currentDate = strtotime($current." + 1 ".$this->increment);
		$this->iterations ++;
	}

	function valid() {
		return $this->currentDate < = $this->endDate;
	}

	function rewind() {
		$this->currentDate = $this->startDate;
	}
	function key() {
		return $this->iterations;
	}
}

Leave a Reply