【问题标题】:Carbon is returning a wrong date? Laravel 5.6碳返回错误的日期?拉拉维尔 5.6
【发布时间】:2018-05-30 06:36:52
【问题描述】:

我在 laravel 中遇到了一个非常奇怪的 Carbon 问题......我正在尝试获得这样的特定日期:

    $now = Carbon::now()->setTimezone('America/Costa_Rica');

    $currentYear = $now->copy()->year;

    $febmon = $now->copy()->month(2)->startOfMonth();
    dd($febmon);

应该返回:2018-02-01 00:00:00.0 America/Costa_Rica (-06:00)

但我却得到了这个:2018-03-01 00:00:00.0 America/Costa_Rica (-06:00)

我已经尝试过所有其他月份的数字,并且效果很好,但是二月......不知道出了什么问题。提前致谢

【问题讨论】:

    标签: php datetime php-carbon laravel-5.6


    【解决方案1】:

    好的,我发现了问题,我的错误,但如果有人遇到这个简单但奇怪的问题:

    我的日期取决于now(),我在设置startOfMonth()之前设置month(2)

    因为今天是 30,所以它会在二月传递到下个月,也就是三月,因为二月没有 30 天,我所要做的就是先设置startOfMonth()...所以它会正确日期。

    这是正确的方法:

    $now = Carbon::now()->setTimezone('America/Costa_Rica');
    
    $febmon = $now->copy()->startOfMonth()->month(2); //Specify the month at last, and set the startOfMonth() first.
    dd($febmon);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-01
      • 2023-03-29
      • 2018-11-12
      • 2018-10-16
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多