Getting the start and end dates of a PHP DatePeriod?

How can I get the start and end date of an object DatePeriod?

$today  = new \DateTime(date('Y-m-d')); // 2012-05-30
$period = new \DatePeriod($today, new \DateInterval('P1M'), 1);

$stats = new UsageStatistics($period);

class UsageStatistics
{

    protected $period, $sentEmailCount, $autoSentEmailCount;

    public function __construct(\DatePeriod $period)
    {
        $this->period = $period;

        // Current logged in user and email repository
        $user = $this->getUser();
        $repo = $this->getEmailRepository();

        // Get the start and end date for the given period
        $startDate = ...
        $endDate   = ...

        $result = $repo->getAllSentCount($user, $startDate, $endDate);

        // Assigning object properties
    }

    public function getSentEmailCount() { return $this->sentEmailCount; }

    public function getAutoSentEmailCount() { return $this->autoSentEmailCount; }
}
+5
source share
3 answers

DatePeriod implements only the Traversable interface and has no other methods for accessing or retrieving elements.

You can do something easy to get start and end dates:

$periodArray = iterator_to_array($period);
$startDate = reset($periodArray);
$endDate = end($periodArray);
+5
source

The solution posted by @hakre and @Boby is incorrect.

$endDate- this is the end of the period when PERIOD % INTERVAL = 0.

All other cases $endDatewill be END - PERIOD.

0
source

PHP 5.6.9, end start DateTime:

$p = new DatePeriod($s, $i, $e);
$startTime = $p->start; //returns $s
$endTime = $p->end; //returns $e

PHP, , . print_r DatePeriod :

DatePeriod Object
(
    [start] => DateTime Object
        (
            [date] => 2015-06-01 00:00:00.000000
            [timezone_type] => 3
            [timezone] => America/Los_Angeles
        )

    [current] => DateTime Object
        (
            [date] => 2015-06-08 00:00:00.000000
            [timezone_type] => 3
            [timezone] => America/Los_Angeles
        )

    [end] => DateTime Object
        (
            [date] => 2015-06-08 00:00:00.000000
            [timezone_type] => 3
            [timezone] => America/Los_Angeles
        )

    [interval] => DateInterval Object
        (
            [y] => 0
            [m] => 0
            [d] => 7
            [h] => 0
            [i] => 0
            [s] => 0
            [weekday] => 0
            [weekday_behavior] => 0
            [first_last_day_of] => 0
            [invert] => 0
            [days] => 
            [special_type] => 0
            [special_amount] => 0
            [have_weekday_relative] => 0
            [have_special_relative] => 0
        )

    [recurrences] => 1
    [include_start_date] => 1
)

, current interval.

0

All Articles