从给定的总年数或总月数中获取每6个月的总天数

时间:2019-08-31 03:47:28

标签: php

我需要从给定的总天数中获取每6个月的总天数。

到目前为止,这是我实现的目标。

  $begin = new DateTime( '2019-08-31' );
  $end = new DateTime( '2020-08-31' );

  // get interval in months
  $interval1 = DateInterval::createFromDateString('6 month');
  $period = new DatePeriod($begin,$interval1,$end);
  $counter = 0;
  foreach($period as $date){
      $counter++;
  }
  echo "counter:".$counter."<br>";

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

  $count = 0;
  foreach($daterange as $date){
      //echo $date->format("Ymd") . "<br>";
      $count++;
  }
  echo "<br>count:".$count;


  for($i=1;$i<=$counter;$i++){

  }

实际结果:

 counter:2

 count:366

我想要实现的目标:

 counter:2

 count:366

 result:182 // for the first 6 months
 result:184 // for the next 6 months

1 个答案:

答案 0 :(得分:0)

对于添加月份,起始日期为day = 31是一个问题。日期时间会像这样添加6个月:

echo date_create("2019-08-31")
  ->modify("+6 Month")
  ->format("Y-m-d")
; //2020-03-02

如果开始是一个月初,则解决方法很简单。 使用DateTime :: diff可以计算整天的差异。

$begin = new DateTime( '2019-08-01' );
$end = new DateTime( '2020-08-01' );
$interval = "6 Month";
$counter = 0;
while($begin < $end){
  $curStart = clone $begin;
  $begin->modify($interval);
  $diffDays = $curStart->diff($begin)->days;
  echo $curStart->format("Y-m-d")." - ".$begin->format("Y-m-d");
  echo ": ".$diffDays." Days<br>";
}

输出

2019-08-01 - 2020-02-01: 184 Days
2020-02-01 - 2020-08-01: 182 Days