问题
I just stumbled upon something really weird. I use the "Carbon" package to generate DateTime objects.
I use the following code to create a DateTime string for the beginning of September 2016:
Carbon::create()->month(9)
If I output this using Laravel's "dd()" function, I receive the following output:
Carbon\Carbon {
+"date": "2016-10-01 10:22:36.000000"
+"timezone_type": 3
+"timezone": "Europe/Vienna"
}
It returns the 1st of October, rather than the 1st of September! It works fine with every other month.
Ive also tried these:
Carbon::now()->month(9)
(new Carbon)->month(9)
But I get the same wrong result.
Does anyone else experience this bug or can someone please try this out and tell me if you receive the same output? Or am I just doing something wrong, even though I can't think of anything?
Thanks in advance.
回答1:
I guess that the problem is todays date which is the 31st.
Carbon::create()->month(9) tries to take the same day for September. Since there is no 31st in September, it returns October 1st. Try:
Carbon::create()->day(1)->month(9);
Or
Carbon::create()->startOfMonth()->month(9);
Or
Carbon::create(null, 9);
来源:https://stackoverflow.com/questions/40339468/php-carbon-month-method-generates-wrong-datetime