Search code examples
phpdatephp-carbon

How to set dynamically a dateperiod/daterange in function of a given date?


I'm searching the way to write a function to set a date period / date interval with a given date....

First, let me explain the context :

I have an application to manage wedding inscriptions. I use for my archives page a system with "seasonnal dates" like

  • 2017-2018
  • 2018-2019
  • 2019-2020 etc.

Each season (or date period) starts the 1st september and finishes the 31 august, so for example 2017-2018 correspond to 2017-09-01 to 2018-08-31, 2018-2019 correspond to 2018-09-01 to 2019-08-31 etc.

So if I have a wedding date like 2019-01-23 I want to save the season corresponding, right here 2018-2019.

Actually I write this code :

    //for example (I have a date object in fact in this $evenement var)
    $evenement = "2019-01-23";
    $start = Carbon::createFromFormat('Y-m-d', $evenement->copy()->subYear()->year . '09-01');
    $end = Carbon::createFromFormat('Y-m-d', $evenement->year . '08-31');
    if($evenement->between($depart, $fin)){
        $saison = $depart->year . '-' . $fin->year;
    }

If the date is after 2019-01-01, it works but not for before and not for the future date, (and not a function at this time)...

Can you help me to achieve this ? It will be very nice.

Thanks


Solution

  • I found the solution during the last night !

    This is my function to get the "season" in function of the given date.

    public static function getSeason($date)
    {
        if($date->month >= 9 && $date->month <= 12){
            $annee1 = $date->year;
            $annee2 = $annee1 + 1;
            $saison = $annee1 . '-' . $annee2;
        }
        elseif($date->month >= 1 && $date->month <= 8){
            $annee2 = $date->year;
            $annee1 = $annee2 - 1;
            $saison = $annee1 . '-' . $annee2;
        }
        return $saison;
    }
    

    So for example, if the date is 2018-10-03,

    $season = "2018-2019";
    

    And if date = 2019-04-21,

    $season = "2018-2019";
    

    What do you think about this function, can I optimize it ?

    Thank you