如何从闰年中减去一年

How to subtract a year from leap year

我正在为以下问题寻找解决方案:

$date = new DateTime('02/29/2020');
$date->sub(new DataInterval('P1Y'));
$date->format('m/d/Y');

这个 Returns:2019 年 3 月 1 日

有办法 return 02/28/2019 吗? 谢谢

date('L') returns 如果是闰年则为真,所以:

<?php

$date = new DateTime('02/29/2020');
$date->format('L') && $date->format('m-d') == '02-29' ? 'P366D' : 'P1Y';
$date->sub(new DateInterval($interval));
echo $date->format('m/d/Y');

在这里查看 https://3v4l.org/4mXX4

挑战一般: 如果日期增加或减少一个月而不跳到下一个月 临近月底了。对于一年,这是加减12个月。

addMonthCut() 函数的算法已采用 here

function addMonthCut(DateTime $date,$month = 1) {
  $dateAdd = clone $date;
  $dateLast = clone $date;
  $strAdd = ' '.(int)$month.' Month';
  $strLast = 'last Day of '.(int)$month.' Month';
  if ($dateAdd->modify($strAdd) < $dateLast->modify($strLast)) {
    $date->modify($strAdd);
  }
  else {
    $date->modify($strLast);
  }
  return $date;
}

示例:

$date = new DateTime('02/29/2020');
$date = addMonthCut($date,-12);  //-1 Year
echo $date->format('m/d/Y');  //02/28/2019

$date = new DateTime('02/28/2019');
$date = addMonthCut($date,+12);  //+1 Year
echo $date->format('m/d/Y');  //02/28/2020

$date = new DateTime('01/31/2020');
$date = addMonthCut($date,+1);  //+1 Month
echo $date->format('m/d/Y');  //02/29/2020