2

我试图弄清楚如何从我设置的日期范围中排除某些日期。日期范围可以正常工作,如下所示:

<?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) "

完整代码(不工作):

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

1 回答 1

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

而已。:)

于 2013-04-21T14:53:04.837 回答