首页 > 解决方案 > 碳返回错误的日期?拉拉维尔 5.6

问题描述

我在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)

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

标签: phpdatetimephp-carbonlaravel-5.6

解决方案


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

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

因为今天是 30,所以它会在 2 月传递到下个月,也就是 3 月,因为 2 月没有 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);

推荐阅读