【发布时间】:2020-02-21 15:13:13
【问题描述】:
我正在寻找以下解决方案:
$date = new DateTime('02/29/2020');
$date->sub(new DataInterval('P1Y'));
$date->format('m/d/Y');
返回:03/01/2019
有没有办法返回 02/28/2019? 谢谢
【问题讨论】:
我正在寻找以下解决方案:
$date = new DateTime('02/29/2020');
$date->sub(new DataInterval('P1Y'));
$date->format('m/d/Y');
返回:03/01/2019
有没有办法返回 02/28/2019? 谢谢
【问题讨论】:
date('L') 如果是闰年则返回 true,因此:
<?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');
【讨论】:
挑战很普遍: 如果日期不跳到下个月,则在日期上加或减一个月 快到月底了。对于一年,这是加减 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
【讨论】: