First day between two dates in php

Question

I want to get the first day of the year between two dates, for example if date1 is 2015-02-01 and date2 is 2017-01-07, the answer will be [2015-01-01, 2016-01-01, 2017-01-01]

I have tried the following for the data above:

$date1_rep_val=2015-02-01;
$date2_rep_val=2017-01-07;
$date1=(new DateTime("$date1_rep_val"))->modify('first day of this year');
$date2=(new DateTime("$date2_rep_val"))->modify('first day of this year');
$interval = DateInterval::createFromDateString('1 year');
$period   = new DatePeriod($date1, $interval, $date2);
$f_cnt=0;
foreach ($period as $dt) 
  {
   $tick_data[$f_cnt]= $dt->format("Y-m-d");
   echo $tick_data[$f_cnt];
   $f_cnt++;
  }

But, the above code gives only 2015-01-01 and 2016-01-01 it is not giving 2017-01-01 , thanks for any help related to this question.


Show source
| date   | php   | intervals   2017-01-07 13:01 2 Answers

Answers to First day between two dates in php ( 2 )

  1. 2017-01-07 14:01

    Why not simply:

    $date1 = '2015-02-01';
    $date2 = '2017-01-07';
    $y1 = substr($date1, 0, 4);
    $y2 = substr($date2, 0, 4);
    $res= array();
    for ($y = $y1; $y <= $y2; $y++) {
        $res[] = $y . "-01-01";
    }
    
  2. 2017-01-07 14:01

    Alternate (but essentially the same) solution with DateTime type using:

    $date1_rep_val='2015-02-01';
    $date2_rep_val='2017-01-07';
    
    $date1 = new DateTime($date1_rep_val);
    $date2 = new DateTime($date2_rep_val);
    
    $year1 = $date1->format('Y');
    $year2 = $date2->format('Y');
    
    $newYearsDates = [];
    if (new DateTime($year1 . '-01-01') == $date1) {
        $newYearsDates[] = $date1;
    }
    
    if ($year2 > $year1) {
        for ($year = $year1 + 1; $year <= $year2; $year++) {
            $newYearsDates[] = new DateTime($year . '-01-01');    
      }
    }
    
    print_r($newYearsDates);
    

Leave a reply to - First day between two dates in php

◀ Go back