在多个月内按月份按比例分配天数



我有一个开始日期和结束日期的例子,下面是2020年12月1日至2021年2月15日

$startDate='2020-12-01'
$endDate='2021-02-15'

我正在努力实现的理想结果:
12月=31天31天=1.0
1月=31天/31天=1.0
2月=15天/28天=0.53
总量=2.53

我的当前公式:
$endDate->diffInDays($startDate(
77/90天*3个月=2.57

$monthPeriod = CarbonPeriod::create($startDate, $endDate)->month();
$yearPeriod = CarbonPeriod::create($startDate, $endDate)->year();
$months = collect($monthPeriod)->map(function (Carbon $date) {
return [
'month' => $date->month,
'name' => $date->format('F'),
'days' => $date->daysInMonth,      
];
});
foreach ($months as $month) {
$quantity = $endDate->diffInDays($startDate)
}
$startDate = Carbon::parse('2020-12-01');
$endDate = Carbon::parse('2021-02-15');
$startDate->floatDiffInMonths($endDate);

如果第15天包括在内,那么你实际上需要增加1天,这样你就可以在午夜16日作为范围的结束:

$startDate->floatDiffInMonths($endDate->addDay());

来自Carbon文档:

echo Carbon::parse('2000-01-15')->floatDiffInMonths('2000-02-24');               // 1.3103448275862
// floatDiffInMonths count as many full months as possible from the start date
// (for instance 31 days if the start is in January), then consider the number
// of days in the months for ending chunks to reach the end date.

最新更新