1
votes

Laravel Carbon obtient la prochaine occurrence d'une date particulière à partir de la date actuelle

Utiliser Carbon avec laravel 5.6.

Je veux écrire un code qui me donne la prochaine occurrence de la date à partir de la date actuelle.

Par exemple, indiquez la date du 31 mai prochain

Scénario 1:
Entrée: $ currentDate = '01 -30-2019 '; // Format MM-JJ-AAAA
Résultats attendus: $ next31May = '05 -31-2019 ';

Scénario 2:
Entrée: $ currentDate = '07 -04-2019 '; // Format MM-JJ-AAAA
Sortie attendue: $ next31May = '05 -31-2020 ';

Update:

J'ai essayé le code ci-dessous mais je n'ai pas satisfait

<?php
public function nextOccurance()
{
    $now = Carbon::now();
    $month= $now->month;
    $year = $now->year;
    if($month > 6)
    {
         echo Carbon::createMidnightDate($year+1, 5, 31);
    }
    else
    {
        echo Carbon::createMidnightDate(null, 5, 31);
    }
    exit();
}
?>

Merci d'avance.


3 commentaires

Qu'as-tu essayé? Avez-vous regardé dans le manuel?


$ maintenant-> addYear (); Utilisez le manuel carbon.nesbot.com/docs/#api-addsub


Pour être juste: ce n'est pas aussi simple que $ now-> addYear ...


4 Réponses :


0
votes

c'est comme avoir le prochain anniversaire.

class Test
{
    public static function getNextBirthday($date)
    {
        // set birthday from current year
        $date = Carbon::createFromFormat('m-d-Y', $date);
        $date->year(Carbon::now()->year);

        // diff from 31 may to now
        // its negative than add one year, otherwise use the current
        if (Carbon::now()->diffInDays($date, false) >= 0) {
            return $date->format('m-d-Y');
        }

        return $date->addYear()->format('m-d-Y');
    }
}

echo Test::getNextBirtday('05-31-1990');


0 commentaires

-2
votes

Carbon fournit une interface agréable et fluide pour ce genre de choses.

Vous pouvez lastOfMonth () pour obtenir le dernier jour du mois. pour ajouter une année, vous pouvez ajouter addYear(1)

  $now = Carbon::now();
    $month= $now->month;
    $year = $now->year;
    if($month > 6)
    {
         echo $now->addMonth(5)->lastOfMonth();
    }
    else
    {
        echo $now->addYear(1);
    }
    exit();
}


0 commentaires

0
votes
public function nextOccurance()
{
    // the 31th of May of the current year
    $day = Carbon::createFromFormat('m-d', '05-31');
    $now = Carbon::now();
    // If today after $day
    if($now >= $day) {
       // Gat a next year
       $day->modify('next year');
    }

    echo $day->format('Y-m-d');
    exit();
}

0 commentaires

0
votes

Je souhaite que cela vous aide à résoudre le problème éclairé.

    $event = Carbon::parse('31 May');

    if (Carbon::now() >= $event){
       $nextEvent  = $event->addYear();
    } else {
       $nextEvent  = $event;
    }

    echo $nextEvent->format('m-d-Y');


0 commentaires