简体   繁体   中英

(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. 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->months means how many months a payment has to be made in total. So, using the for loop, the current date is being checked against the starting date.

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? 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:

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 .

If I understood correctly, you want to check if the "start date plus few months" is between now and 5 days before now. In this case, you can do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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