php中两个日期之间的第一天

时间:2017-01-07 12:41:05

标签: php date intervals

我希望在两个日期之间获得一年中的第一天,例如 date1 2015-02-01 和< strong> date2 2017-01-07 ,答案将是[ 2015-01-01 2016-01-01 2017-01-01 ]

我已尝试以下数据:

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

但是,上面的代码只给出 2015-01-01 2016-01-01 它没有给出 2017-01-01 ,感谢您对此问题的任何帮助。

2 个答案:

答案 0 :(得分:2)

为什么不简单:

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

答案 1 :(得分:0)

使用DateTime类型替换(但基本上相同)的解决方案:

$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);