2013-01-09 12 views
0

我正在準備一個節日網站。我有一個日期時間字段的節日日期表。 節日將介於「2013年6月/ 2013年」和「2013年4月7日」之間。 所以我創建的循環在這些答案在這裏:如何從循環中獲取所有日期

Schema::create('dates',function($table) 
     { 
      $table->increments('id'); 
      $table->date('date'); 
      $table->timestamps(); 
     }); 
     $starting_date = new DateTime('2013-03-06'); 
     $ending_date = new DateTime('2013-04-06'); 

     $interval = DateInterval::createFromDateString('1 day'); 
     $period = new DatePeriod($starting_date , $interval, $ending_date); 

     foreach($period as $dt) 
     { 

     DB::table('dates')->insert(array(
     'date' => $dt 
     )); 

     } 

數據庫被填充到4 4,循環不添加超過30天。 你能幫我找到一個修復失蹤的日子嗎?

PS:我用的替代while循環導致相同:

$starting_date = new DateTime('2013-03-06');   
      $ending_date = new DateTime('2013-04-07'); 

      while($starting_date <= $ending_date){ 
       DB::table('dates')->insert(array(
        'date' => $starting_date 
       )); 

      } 
    $starting_date->add(new DateInterval('P1D')); 
} 
+0

你嘗試過一段時間(的strtotime ($ starting_date)<= strtotime($ ending_date))? –

+0

我應用了您的建議。 strtotime()期望參數1是字符串...我得到這個錯誤。 – ytsejam

+1

將時間傳遞給'strtotime'時不要使用'DateTime'對象。例如:'$ starting_date ='2013-03-06'' – vanneto

回答

1
just add 23:59:59 to the end of the $ending_date 
$starting_date = new DateTime('2013-03-06 00:00'); 
$ending_date = new DateTime('2013-04-06 23:59:59'); 


$interval = new DateInterval('P1D'); 
$period = new DatePeriod($starting_date , $interval, $ending_date); 
foreach ($period as $date) { 
    echo $date->format('Y-m-d')."<br/>"; 
} 
print_r($period);exit; 

其輸出

2013年3月6日2013年3月7日

2013年3月8日
2013年3月9日2013年3月10日

2013年3月11日2013
-03-12
2013年3月13日
2013年3月14日
2013年3月15日
2013年3月16日
2013年3月17日
2013年3月18日
2013年3月19日
2013-03 -20
2013-03-21
2013-03-22
2013-03-23
2013年3月24日
2013年3月25日
2013年3月26日
2013年3月27日
2013年3月28日
2013年3月29日
2013年3月30日
2013 -03-31
2013年4月1日
2013年4月2日
2013年4月3日
2013年4月4日
2013年4月5日
2013年4月6日

+0

謝謝解決了我的問題。 – ytsejam

2

我想出了一個非常快速和骯髒的解決方案是:

$starting_date = strtotime('2013-03-06'); 
$ending_date = strtotime('2013-04-06'); 

while($starting_date <= $ending_date) 
{ 
    echo date('d/m/y', $starting_date) . '<br />'; 
    $starting_date = strtotime('1 day', $starting_date); 
} 

,輸出:

06/03/13 
07/03/13 
08/03/13 
09/03/13 
10/03/13 
11/03/13 
12/03/13 
13/03/13 
14/03/13 
15/03/13 
16/03/13 
17/03/13 
18/03/13 
19/03/13 
20/03/13 
21/03/13 
22/03/13 
23/03/13 
24/03/13 
25/03/13 
26/03/13 
27/03/13 
28/03/13 
29/03/13 
30/03/13 
31/03/13 
01/04/13 
02/04/13 
03/04/13 
04/04/13 
05/04/13 
06/04/13 

您可以簡單地用您的查詢替換回顯。

+0

仍然給我30天的這種方法。直到4月4日 – ytsejam

+0

基於我的例子,它返回超過30,但是如果它只是「插入」30,這可能是數據庫的限制。 1)確保顯示錯誤,即'ini_set('display_errors',1); error_reporting(E_ALL);'然後添加'echo date('d/m/y',$ starting_date)。 '
';'在數據庫插入之下。我懷疑你沒有看到數據庫錯誤。 – Gavin

相關問題