简体   繁体   English

如果我认为每个月只有第 30 天,如何获得两个日期之间的差异天数

[英]how to get diff days between two dates if I consider every month is day 30 only

$start_date = Carbon::parse(date('Y-m-d', strtotime('2022-08-17')));
$end_date = Carbon::parse(date('Y-m-d', strtotime('2022-09-01')));
$diff = $start_date->diffInDays($end_date);

Days between these two dates is 15 , because aug is 31 day but in my case I consider every month is 30 day, so the difference should be 14这两个日期之间的天数是15 ,因为 aug 是 31 天,但在我的情况下,我认为每个月都是 30 天,所以差异应该是14

Carbon has a daysInMonth attribute which returns the number of days for a given date. Carbon 有一个daysInMonth属性,它返回给定日期的天数。 So you could use that and do something like the following:因此,您可以使用它并执行以下操作:

public function diffInDays($start_date, $end_date)
{
    $diff = $start_date->diffInDays($end_date);

    $daysInMonths = [$start_date->daysInMonth, $end_date->daysInMonth];

    foreach ($daysInMonths as $count) {
        if ($count >= 31) {
            $diff--;
        }
    }

    return $diff;
}

Then you would use the above as follows:然后你会使用上面的如下:

$start_date = \Carbon\Carbon::parse(date('Y-m-d', strtotime('2022-08-17')));
$end_date = \Carbon\Carbon::parse(date('Y-m-d', strtotime('2022-09-01')));

$diff = $this->diffInDays($start_date, $end_date);

This could be improved upon but the principle works as desired.这可以改进,但原理按需要工作。 The result is 14 .结果是14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM