2012-05-30 219 views
5

我如何獲得DatePeriod對象的開始和結束日期?獲取PHP 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

DatePeriod只實現Traversable接口,沒有其他方法來訪問元素或檢索它們。

你可以做一些輕鬆搞定開始/結束日期:

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

很醜,你必須循環。不管怎麼說,還是要謝謝你。 – gremo

+0

是的,我知道,我用ArrayObject嘗試過,但它沒有奏效。 – Boby

+1

有趣的是,知道我正在尋找完全一樣的。看來,有一個補丁在那裏https://bugs.php.net/bug.php?id=53439但它是從2010年,所以...不知道 – KingCrunch

0

該解決方案通過@hakre發佈和@Boby是不正確的。

$endDate是期末PERIOD % INTERVAL = 0。所有其他案例將END - PERIOD

0

我使用PHP 5.6.9,似乎你可以使用屬性endstart訪問您的開始和結束DateTime對象:

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

的PHP文件似乎並沒有反映這一點。我做了DatePeriod對象的print_r,得到了以下的輸出:

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也是可見的。

+0

注意:在PHP 5.3中,'end'屬性保持爲空 –

相關問題