简体   繁体   English

(Laravel)根据开始日期检查今天是否在两个日期之间

[英](Laravel) check if today is between two dates based on a starting date

I have a payments table where I keep track of certain payments. 我有一张付款表,可以跟踪某些付款。 Let's say I have a start date, which can be any date. 假设我有一个开始日期,可以是任何日期。 Payments will have to be made each month. 每个月都要付款。

For example, I want to track if a payment is due 5 days before it needs to be made. 例如,我想在需要付款前5天跟踪付款是否到期。 This will be checked on a daily basis. 这将每天检查。 For this I use the following method: 为此,我使用以下方法:

public function isDue()
{
    for ($i = 0; $i <= $this->months; $i++) {

        if (Carbon::now()->format('Y-m-d') >= Carbon::createFromFormat('Y-m-d', $this->start)->addMonthsNoOverflow($i)->subDays(5)->format('Y-m-d')
            &&
            Carbon::now()->format('Y-m-d') <= Carbon::createFromFormat('Y-m-d', $this->start)->addMonthsNoOverflow($i)->format('Y-m-d')
        ) {
            return true;
        }
    }
    return false;
}

$this->start is the starting date. $this->start是开始日期。 $this->months means how many months a payment has to be made in total. $this->months表示必须支付多少个月的费用。 So, using the for loop, the current date is being checked against the starting date. 因此,使用for循环,将根据开始日期检查当前日期。

My question basically is, since I want to make this foul proof, is there good way to accomplish this, or will something like a for loop and such work? 我的问题基本上是,因为我想做出这样的防守,是否有很好的方法来实现这一目标,还是会像for循环这样的工作? The above code just feels sloppy to me and it will not produce the correct results I'm afraid. 上面的代码对我来说感觉很草率,它不会产生我害怕的正确结果。

Carbon has a few other helper methods for comparison including isToday() that you can use: Carbon有一些其他帮助方法可供比较,包括isToday() ,你可以使用:

public function isDue()
{
    for ($i = 0; $i < $this->months; $i++) {
        if ($this->start_date->addMonthsNoOverflow($i)->subDays(5)->isToday()) {
            return true;
        }
    }

    return false;
}

This will create a loop for each month as you did before, and check that the adjusted date is today. 这将像以前一样为每个月创建一个循环,并检查调整后的日期是否为今天。 If it is, the method immediately returns true . 如果是,则该方法立即返回true

If I understood correctly, you want to check if the "start date plus few months" is between now and 5 days before now. 如果我理解正确,你想检查“开始日期加几个月”是从现在到现在的5天之间。 In this case, you can do this: 在这种情况下,您可以这样做:

if ($this->start->addMonthsNoOverflow($i)->between(now()->subDays(5), now()))

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

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