简体   繁体   中英

Get total number of days every 6 months from given total number of years or months

I need to get the total number of days every 6 months from the given total number of days.

So far this is what I achieved.

  $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++){

  }

Actual result:

 counter:2

 count:366

What I want to achieve:

 counter:2

 count:366

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

For add month, a start date with day = 31 is a problem. Datetime adds 6 month like this:

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

If the start is at the beginning of a month, the solution is simple. With DateTime::diff the difference can be calculated in full days.

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

Outputs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM