【问题标题】:Getting months from now and a couple of months ago几个月后和几个月前
【发布时间】:2021-03-08 22:16:21
【问题描述】:

我试图从这个月一直到去年的月份名称,但我不知道如何得到它。

我有

$now = Carbon::now();
$past = Carbon::now()->subMonths(4);

但我不认为这是正确的。

【问题讨论】:

标签: laravel


【解决方案1】:

您可以使用 Carbon 中的 DatePeriod,只需获取从年初到现在的 DatePeriod,使用 DateInterval 作为月份:

 $value=collect(
          new DatePeriod(Carbon::now()->firstOfYear(), new DateInterval('P1M'),Carbon::now() ))->map(function ($month) {
          return $month->format('M');
      });

【讨论】:

    【解决方案2】:

    使用CarbonPeriod类做同样的事情

    use Carbon\CarbonPeriod;
    
    $oneYearAgo = new CarbonPeriod('2020-03-08', '1 month', '2021-03-08');
    
    foreach ($oneYearAgo as $month) {
        $month->format("M"); //Mar
    }
    

    您可以找到更多信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 2011-11-19
      • 2016-11-17
      • 2021-06-28
      • 1970-01-01
      相关资源
      最近更新 更多