在php中获取包含月份开始日期和结束日期的月度数组

时间:2017-08-22 06:21:42

标签: php arrays date

我们已经创建了Weekly数组

[1] =>排列            (                [开始] => 2017年1月1日                [end] => 2017年1月7日            )

但我们需要每月的数组开始日期和月结束日期

就像这样

Array
   (
       [1] => Array
           (
               [start] => 2017-01-01
               [end] => 2017-02-01
           )

       [2] => Array
           (
               [start] => 2017-02-01
               [end] => 2017-03-01
           )

       [3] => Array
           (
               [start] => 2017-03-01
               [end] => 2017-04-01
           )

       [4] => Array
           (
               [start] => 2017-04-01
               [end] => 2017-05-01
           )

       [5] => Array
           (
               [start] => 2017-05-01
               [end] => 2017-06-01
           )

   )

1 个答案:

答案 0 :(得分:2)

我们正在使用DateTimeDateInterval来实现预期的输出。

Try this code snippet here

<?php
ini_set('display_errors', 1);

$startDate="2017-01-01";
$endDate="2017-06-01";

$dates=array();
while($startDate!=$endDate)
{
    $monthEndDate=new DateTime($startDate);
    $monthEndDate->add(new DateInterval("P1M"));//adding one month each time we iterate
    $dates[]=array("start" => $startDate,
                   "end" => $monthEndDate->format("Y-m-d"));
    $startDate=$monthEndDate->format("Y-m-d");//changing start date
}
print_r($dates);