5

如何获取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; }
}
4

4 回答 4

5

DatePeriod仅实现 Traversable 接口,没有其他方法可以访问或检索元素。

您可以做一些简单的事情来获取开始/结束日期:

$periodArray = iterator_to_array($period);
$startDate = reset($periodArray);
$endDate = end($periodArray);
于 2012-05-30T15:03:59.957 回答
1

我正在使用 PHP 5.6.9,您似乎可以使用这些属性endstart访问您的开始和结束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
)

似乎属性currentinterval也是可见的。

于 2015-06-08T19:50:24.323 回答
0

@hakre 和 @Boby 发布的解决方案不正确。

是期间的$endDate结束PERIOD % INTERVAL = 0

所有其他情况$endDate都是END - PERIOD.

于 2013-09-13T21:21:44.637 回答
0
$startingDate = new DateTime($startingDay);
$startingDate->modify('previous day');
$startingDate->modify('next Sunday');
     
$endingDate   = new DateTime($endingDay);
$endingDate->modify('next day');
   
$period = new DatePeriod($startingDate, new DateInterval('P1W'), $endingDate);
于 2021-03-28T20:22:56.123 回答