从日期范围中排除日期


php: exclude dates from a date range

我想弄清楚如何从我设置的日期范围中排除某些日期。日期范围如下所示:

<?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所要求的,我已经添加了get_field('test_select'));var_dump()

var_dump(get_field('test_select'));
结果:

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

完整代码(不工作):

$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") . " ";
    }   
}

无法使用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

更新:

在评论中,你问如何将传入的日期字符串列表转换为可以在$exclude数组中使用的DateTime对象。

的例子:

$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);
}

就是这样。:)