【问题标题】:Prorate days in months across multiple months在多个月中按月按比例分配天数
【发布时间】:2021-05-20 15:47:37
【问题描述】:

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

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

我想要达到的理想结果:
12 月 = 31 天 31 天 = 1.0
一月 = 31 天 / 31 天 = 1.0
二月 = 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)
}

【问题讨论】:

  • 您是指 2019 年 12 月吗?
  • 我的错误,我已经编辑了我的结束日期

标签: php laravel php-carbon


【解决方案1】:
$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.

【讨论】:

  • 这是否解决了如何考虑2月=15天/28天=0.53部分的问题
  • 如果您将午夜 16 点视为范围的结束,您将得到 2.53。仔细检查你的公式,你确定 2 月 1 日到 28 日应该给你 1(而不是 27/28)吗?
  • 我建议 $endDate->addDay()->subSecond() 更准确,但是是的 @NigelRen 它确实给出了 OP 想要的 2.53571 答案
  • 在这种情况下,只需使用$endDate->endOfDay(),但它实际上并不更准确,因为它不是一整天。如果您希望 1 月 1 日至 31 日正好是 1 个月,则使用次日午夜是正确的选择。减去 1 秒,1 到 31 变成 0.99999 我想这不是我们可以说的准确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
相关资源
最近更新 更多