如何在php中获取两个日期之间的星期三日期

如何在php中获取两个日期之间的星期三日期,php,Php,需要获取两个日期之间的所有星期三日期。前 开始和结束日期= 01/07/2019 - 01/25/2019 预期结果= 01/09/2019, 01/16/2019, 01/23/2019 如果($startDate->format('w')==2,{} 条件筛选星期三并推入阵列。有什么方法可以得到结果吗?请使用。date period允许在一组日期和时间上进行迭代,在给定的时间段内定期重复 $period = new DatePeriod( new DateTime($date1

需要获取两个日期之间的所有星期三日期。前 开始和结束日期=

01/07/2019 - 01/25/2019
预期结果=

01/09/2019,
01/16/2019,
01/23/2019
如果($startDate->format('w')==2,{} 条件筛选星期三并推入阵列。有什么方法可以得到结果吗?

请使用。date period允许在一组日期和时间上进行迭代,在给定的时间段内定期重复

$period = new DatePeriod(
     new DateTime($date1),
     new DateInterval('P1D'),
     new DateTime($date2)
);

$cnt = 0;
foreach ($period as $key => $value) {

    if($value->format('D') == 'Wed'){
        $wed[$cnt] = $value->format('m/d/Y');
        $cnt++;
    }   
}
输出

[0] => 01/09/2019
[1] => 01/16/2019
[2] => 01/23/2019
使用。date period允许在一组日期和时间上进行迭代,在给定的时间段内定期重复

$period = new DatePeriod(
     new DateTime($date1),
     new DateInterval('P1D'),
     new DateTime($date2)
);

$cnt = 0;
foreach ($period as $key => $value) {

    if($value->format('D') == 'Wed'){
        $wed[$cnt] = $value->format('m/d/Y');
        $cnt++;
    }   
}
输出

[0] => 01/09/2019
[1] => 01/16/2019
[2] => 01/23/2019

您将获得所需的输出

<?php

$date1 = date("01/07/2019");
$date2 = date("01/25/2019");
$day1 = date('D', strtotime($date1));
$period = new DatePeriod(New Datetime($date1),New DateInterval('P1D'),New DateTime($date2));

$cnt = 0;
foreach($period as $key => $value ){

  if($value->format('D') == 'Wed'){
        $wed[$cnt] = $value->format('m/d/Y');
        echo $wed[$cnt];        
        $cnt++;
        echo '<BR>';  

    } 

}



?>

您将获得所需的输出

<?php

$date1 = date("01/07/2019");
$date2 = date("01/25/2019");
$day1 = date('D', strtotime($date1));
$period = new DatePeriod(New Datetime($date1),New DateInterval('P1D'),New DateTime($date2));

$cnt = 0;
foreach($period as $key => $value ){

  if($value->format('D') == 'Wed'){
        $wed[$cnt] = $value->format('m/d/Y');
        echo $wed[$cnt];        
        $cnt++;
        echo '<BR>';  

    } 

}



?>

使用基本的
日期时间
类,而不是每天检查,只需在日期上增加7天,并检查是否仍然小于结束日期。唯一的附加逻辑是,如果开始日期是星期三,则使用此日期,否则使用下一个星期三

$fromDate = new DateTime('01/02/2019');
if ( $fromDate->format('D') != 'Wed')   {
    $fromDate->modify("next wednesday");
}
$toDate = new DateTime('01/25/2019');
do {
    echo $fromDate->format("m/d/Y").PHP_EOL;
} 
while ( $fromDate->modify(""+7 day"") < $toDate );

使用base
DateTime
类,不必每天检查,只需在日期上增加7天,然后检查是否仍然小于结束日期。唯一的附加逻辑是,如果开始日期是星期三,则使用此日期,否则使用下一个星期三

$fromDate = new DateTime('01/02/2019');
if ( $fromDate->format('D') != 'Wed')   {
    $fromDate->modify("next wednesday");
}
$toDate = new DateTime('01/25/2019');
do {
    echo $fromDate->format("m/d/Y").PHP_EOL;
} 
while ( $fromDate->modify(""+7 day"") < $toDate );

如果发现答案有用,您可以将其标记为有效答案。如果发现答案有用,您可以将其标记为有效答案