Date/Time
在线手册:中文 英文
PHP手册

The DatePeriod class

(PHP 5 >= 5.3.0)

简介

Representation of date period.

类摘要

DatePeriod implements Traversable {
/* 常量 */
const integer EXCLUDE_START_DATE = 1 ;
/* 方法 */
public __construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
public __construct ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
public __construct ( string $isostr [, int $options ] )
}

预定义常量

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().

Table of Contents


Date/Time
在线手册:中文 英文
PHP手册
PHP手册 - N: The DatePeriod class

用户评论:

Aurelien Marchand (09-Mar-2011 08:11)

Warning About DatePeriod for Some Versions of PHP
*****************************************

Some versions of PHP had a bug so that caused DatePeriod to act strangely. For instance, the following code:

<?php
$start
= DateTime::createFromFormat("Y-m-d H:i:s","2011-01-01 00:00:00",new DateTimeZone("America/Toronto"));
$interval = new DateInterval("P1M"); // 1 month
$occurrences = 3;
$period = new DatePeriod($start,$interval,$occurrences);
foreach(
$period as $dt){
  echo
$dt->format("Y-m-d H:i:s") . "\n";
}
foreach(
$period as $dt){
  echo
$dt->format("Y-m-d H:i:s") . "\n";
}
?>

Would produce the following text:
2011-01-01 00:00:00
2011-02-01 00:00:00
2011-03-01 00:00:00
2011-04-01 00:00:00
2011-05-01 00:00:00
2011-06-01 00:00:00
2011-07-01 00:00:00
2011-08-01 00:00:00

Instead of:
2011-01-01 00:00:00
2011-02-01 00:00:00
2011-03-01 00:00:00
2011-04-01 00:00:00
2011-01-01 00:00:00
2011-02-01 00:00:00
2011-03-01 00:00:00
2011-04-01 00:00:00

5.3.2 fails
5.3.3 fails
5.3.4 -??-
5.3.5 works

Memori (25-Feb-2011 08:19)

If you want to include the end-date, add one day to it:

<?php
$startDate
= new DateTime();
$endDate = new DateTime();

$startDateInt = new DateInterval( "P1Y" );
$endDateInt = new DateInterval( "P1D" );

$startDate->sub( $startDateInt );
$endDate->add( $endDateInt );

$periodInt = new DateInterval( "P1M" );
$period = new DatePeriod( $startDate, $periodInt, $endDate );

// At februari 2011:
// $period = (8,9,10,11,12,1,2)
?>

jkaatz at gmx dot de (10-Jul-2009 09:55)

Nice example from PHP Spring Conference (thanks to Johannes Schlüter and David Zülke)

<?php
$begin
= new DateTime( '2007-12-31' );
$end = new DateTime( '2009-12-31 23:59:59' );

$interval = DateInterval::createFromDateString('last thursday of next month');
$period = new DatePeriod($begin, $interval, $end, DatePeriod::EXCLUDE_START_DATE);

foreach (
$period as $dt )
  echo
$dt->format( "l Y-m-d H:i:s\n" );
?>

DateInterval specs could be found at http://en.wikipedia.org/wiki/ISO_8601#Time_intervals