【问题标题】:How to get dates between two dates into array with DateTime如何使用 DateTime 将两个日期之间的日期放入数组中
【发布时间】:2014-01-28 20:03:00
【问题描述】:

我在这里要做的是从 3 个月范围内获取具有特定条件的日期,并将它们放入数组中。

获取日期:

$begin = new DateTime( 'NOW' );
$end = new DateTime('NOW');
$end->modify('+6 month');

$interval = new DateInterval('P1D');
$period = new DatePeriod($begin, $interval ,$end);

过滤器以获取我的标准日期:

foreach ( $period as $dt ){
    if ((!($dt->format("l") === 'Saturday') || ($dt->format("l") === 'Sunday')) && ($dt->format("d") == '14')){
        $meeting = $dt->format( "Y-m-d" );
        echo $dt->format( "Y-m-d" ) . '<br />';

    }

    if((($dt->format("l") === 'Saturday') || ($dt->format("l") === 'Sunday')) && ($dt->format("d") == '14')){
        $dt->modify('Next monday');
        echo $dt->format( "Y-m-d" ) . '<br />';

    }   
}

echo '<hr>';
$interval_2 = new DateInterval('P1M');
$period_2 = new DatePeriod($begin, $interval_2 ,$end);

foreach ( $period_2 as $dt ){
    $dt->modify('last day of this month');  
    //echo $dt->format( "l Y-m-d\n" ) . '<br />';
    if(($dt->format("l") === 'Saturday') || ($dt->format("l") === 'Sunday') || ($dt->format("l") === 'Friday')){
        $dt->modify('previous Thursday');
        echo $dt->format( "Y-m-d" ) . '<br />';
    } else {
        echo $dt->format( "Y-m-d" ) . '<br />';
    }


}

所有这一切都很完美,但它们只是显示,我想将它们放入数组中以使用 fputcsv 将它们放入 CSV 文件中,所以我需要它们:

Month, first_date, second_date

我怎样才能做到这一点?

【问题讨论】:

    标签: php arrays date datetime


    【解决方案1】:

    通过声明解决了我的问题:

    $meet = array();
    $test = array();
    

    然后在每个if:

    $meet[] = $dt->format( "Y-m-d" );
    $test[] = $dt->format( "Y-m-d" );
    

    这样,如果你创建了一个 var_dump,它就会为它们中的每一个提供一个数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-02
      • 2019-05-07
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多