【问题标题】:Laravel Carbon get next occurrence of particular date from current dateLaravel Carbon 从当前日期获取特定日期的下一次出现
【发布时间】:2019-06-18 05:38:21
【问题描述】:

在 laravel 5.6 中使用 Carbon。

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

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

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

场景 2:
输入:$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();
}
?>

提前谢谢你。

【问题讨论】:

标签: php laravel datetime php-carbon


【解决方案1】:

这就像得到下一个生日。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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();
      }
      

      【讨论】:

        【解决方案4】:

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

            $event = Carbon::parse('31 May');
        
            if (Carbon::now() >= $event){
               $nextEvent  = $event->addYear();
            } else {
               $nextEvent  = $event;
            }
        
            echo $nextEvent->format('m-d-Y');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-04-28
          • 2015-09-28
          • 2017-07-06
          • 1970-01-01
          • 2016-10-04
          • 2017-01-08
          • 1970-01-01
          相关资源
          最近更新 更多