Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nickdavies07's avatar

Carbon - Get Date Depending on now() value

I'm creating a scope in my model for retrieving values from a database between two dates.

So far, I have this which retrieves entries between 1st Sept 2018 and now. However, I need the first date's year to vary depending on the current date.

I basically need to go back from today to the 1st September 20{xx} depending on the current year, so if it's 26th November 2018, I need to get 1st September 2018, until now() gets passed 1st September 2019, then it should get values between 1st September 2019 and e.g. 7th September 2019.

This is what I have so far, I'm just not sure on how to use Carbon to get the correct date I'm looking for.

    public function scopeResolvedThisAcademicYear($query)
    {
        return $query->whereBetween('resolved_on', ['2018-09-01', Carbon::now()]);
    }

Any help would be hugely appreciated!

0 likes
3 replies
D9705996's avatar

You can get the 1st September of the current year with the following (from the docs)

Carbon::createFromDate(null, 9, 1)

This gives the following in tinker

>>> Carbon\Carbon::createFromDate(null, 9, 1);
=> Carbon\Carbon @1567347837 {#3292
     date: 2019-09-01 14:23:57.0 UTC (+00:00),
   }

MikeMacDowell's avatar
Level 25

@nickdavies07 try

Carbon::createMidnightDate(Carbon::now()->subMonths(8)->year, 9, 1)

This gets the current date, removes 8 months from it to get the correct year as your "year" starts on 1st September and then creates a midnight time date for the 1st September that year

nickdavies07's avatar

@MIKEMACDOWELL - Brilliant!

So simple, didn't think about it that way. Works like a charm. Thanks

    public function scopeResolvedThisAcademicYear($query)
    {
        $start = Carbon::createMidnightDate(Carbon::now()->subMonths(8)->year, 9, 1);
        $end = Carbon::now();
        return $query->whereBetween('resolved_on', [$start, $end]);
    }

Please or to participate in this conversation.