我想弄清楚如何從我設置的日期範圍中排除某些日期。該日期範圍內正常工作,像這樣: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") . " ";
}
}
一條建議 - 不要使用可能含糊不清的日期格式。 '7/12/2010'可能是7月12日,但對我來說,這意味着12月7日。並且要注意,模糊的輸入會導致PHP假定錯誤的值。如果可能,請始終在您的代碼中使用不含混淆的日期格式。如果不可能,請使用'DateTime :: CreateFromFormat()',並使用顯式指定的格式。 – Spudley 2013-04-21 15:57:52