2013-04-21 99 views
2

我想弄清楚如何從我設置的日期範圍中排除某些日期。該日期範圍內正常工作,像這樣:php:排除日期範圍內的日期

<?php $newBegin = new DateTime('6/30/2010'); 
$newEnd = new DateTime('7/12/2010'); 
$newEnd = $newEnd->modify('+1 day'); 

$newDaterange = new DatePeriod($newBegin, new DateInterval('P1D'), $newEnd); 

foreach($newDaterange as $newDate){ 
    echo $newDate->format("jnY") . " "; 
} ?> 

打印出結果,像這樣:

3062010 172010 272010 372010 472010 572010 672010 772010 872010 972010 1072010 1172010 1272010 

,但客戶端將需要從每個日期範圍中排除某些日期,所以我最好喜歡輸入如下日期:7/2/2010 7/4/2010 8/4/2010並從日期範圍中排除它們。這是可能嗎?我不打算排除週末等,我可以這樣做,只需輸入一組日期並從日期範圍中排除它們即可。任何建議將不勝感激!


更新:

正如@ hek2mgl問這個問題,我已經添加var_dump()get_field('test_select'));

var_dump(get_field('test_select')); 

一個結果:

array(2) { [0]=> string(8) "7/2/2010" [1]=> string(8) " 

的完整代碼(不是w orking):

$newBegin = DateTime::createFromFormat('n/j/Y', '6/30/2010'); 
$newEnd = DateTime::createFromFormat('n/j/Y', '7/12/2010'); 
$newEnd = $newEnd->modify('+1 day'); 

$exclude = array(); 

// stores dates like so: 7/2/2010 7/3/2010 
foreach(get_field('test_select') as $datestring) { 
    $exclude []= new DateTime($datestring); 
} 

$newDaterange = new DatePeriod($newBegin, new DateInterval('P1D'), $newEnd); 

foreach($newDaterange as $newDate){ 
    if(!in_array($newDate, $exclude)) { 
     echo $newDate->format("jnY") . " "; 
    } 
} 
+1

一條建議 - 不要使用可能含糊不清的日期格式。 '7/12/2010'可能是7月12日,但對我來說,這意味着12月7日。並且要注意,模糊的輸入會導致PHP假定錯誤的值。如果可能,請始終在您的代碼中使用不含混淆的日期格式。如果不可能,請使用'DateTime :: CreateFromFormat()',並使用顯式指定的格式。 – Spudley 2013-04-21 15:57:52

回答

3

無法使用DatePeriod類排除某個範圍內的多個日期。但是,您可以使用in_array()DateTime對象。這可能會導致這樣的代碼:

$newBegin = new DateTime('6/30/2010'); 
$newEnd = new DateTime('7/12/2010'); 
$newEnd = $newEnd->modify('+1 day'); 

$exclude = array(
    new DateTime('7/2/2010'), 
    new DateTime('7/4/2010'), 
    new DateTime('8/4/2010') 
); 

$newDaterange = new DatePeriod($newBegin, new DateInterval('P1D'), $newEnd); 

foreach($newDaterange as $newDate){ 
    if(!in_array($newDate, $exclude)) { 
     echo $newDate->format("jnY") . " "; 
    } 
} 

輸出:

3062010 172010 372010 572010 672010 772010 872010 972010 1072010 1172010 1272010 

更新:

在你問如何日期字符串的來電列表翻譯成評論DateTime可以在$exclude陣列中使用的對象。

例子:

$exclude = array(); 

// stores dates like so: 7/2/2010 7/3/2010 
foreach(get_field('test_select') as $datestring) { 
    $exclude []= new DateTime::createFromFormat('n/j/Y', $datestring); 
} 

就是這樣。 :)

+0

非常感謝你!這幾乎是完美的,只有一件小事情,因爲排除日期(在數組中)將被用戶輸入到前端,而不是像上面的例子那樣的後端,是否有可能爲'new DateTime('7/2/2010'),'get_field('test_select');'用戶在'test_select'字段輸入日期? – user1374796 2013-04-21 16:04:56

+0

如果'test_select'包含日期字符串parseble by'DateTime',則使用'new DateTime(get_field('test_select'));' – hek2mgl 2013-04-21 16:51:18

+0

很好,我已經調整了一點,我承諾的最後一個問題是,'test_select'字段現在打印一個日期數組。例如'echo echo implode('',get_field('test_select'));'顯示如下所示的日期:'2010年7月3日7/3/2010'是否可以從日期範圍中排除這些日期?我仍然很新的PHP,所以我不是100%確定它將如何寫... – user1374796 2013-04-21 20:38:13