Skip to content
Advertisement

Getting start and end date of a PHP DatePeriod object?

How can i get the start and end date of a DatePeriod object?

$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; }
}

Advertisement

Answer

DatePeriod only implements the Traversable interface and has no other methods to either access elements or retrieve them.

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

$periodArray = iterator_to_array($period);
$startDate = reset($periodArray);
$endDate = end($periodArray);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement