gpt4 book ai didi

php - 2 月 29 日加上 12 个月

转载 作者:行者123 更新时间:2023-12-03 01:04:58 24 4
gpt4 key购买 nike

我想将我的约会时间延长 12 个月。我的开始日期是 2020 年 2 月 29 日,我想在此基础上添加 12 个月。

代码:

$startdate = '02/29/2020';
date('m/d/Y', strtotime('+12 months', strtotime($startdate)));

输出:

03/01/2021

我使用此代码添加了 12 个月,但输出为 03/01/2021,而实际输出应为 02/28/2020

最佳答案

看看吧!

 function add_months($months, DateTime $dateObject) 
{
$next = new DateTime($dateObject->format('Y-m-d'));
$next->modify('last day of +'.$months.' month');

if($dateObject->format('d') > $next->format('d')) {
return $dateObject->diff($next);
} else {
return new DateInterval('P'.$months.'M');
}
}

function getCalculatedDate($d1, $months)
{
$date = new DateTime($d1);

// call second function to add the months
$newDate = $date->add(add_months($months, $date));

//formats final date to m/d/Y form
$dateReturned = $newDate->format('m/d/Y');

return $dateReturned;
}

一个例子是:-

$startDate = '02/29/2020';
$nMonths = 12; // choose how many months you want to add
$finalDate = getCalculatedDate($startDate, $nMonths); // output: 02/28/2021

这样您将获得 02/28/2021 的输出

关于php - 2 月 29 日加上 12 个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60294011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com