繁体   English   中英

Laravel Carbon 从当前日期获取特定日期的下一次出现

[英]Laravel Carbon get next occurrence of particular date from current date

在laravel 5.6 中使用Carbon。

我想编写一个代码,让我从当前日期开始下一次出现日期。

例如给出下一个 5 月 31 日的日期

场景一:
输入:$currentDate = '01-30-2019'; // MM-DD-YYYY 格式
预期输出:$next31May = '05-31-2019';

场景二:
输入:$currentDate = '07-04-2019'; // MM-DD-YYYY 格式
预期输出:$next31May = '05-31-2020';

更新:

我试过下面的代码但不满意

<?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();
}
?>

先感谢您。

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();
}

这就像得到下一个生日。

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');

我希望这将帮助您解决知情问题。

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

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

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

Carbon 为这类东西提供了一个很好且流畅的界面。

您可以lastOfMonth()获取一个月的最后一天。 要添加年份,您可以添加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();
}

暂无
暂无

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

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