briannesbitt / Carbon

A simple PHP API extension for DateTime.
https://carbon.nesbot.com/
MIT License
16.59k stars 1.28k forks source link

Error parsing date #3012

Closed tapacko88 closed 7 months ago

tapacko88 commented 7 months ago

Hello,

I encountered an issue with the following code:

echo Carbon::createFromFormat('M Y', 'Feb 2024')->format('Y-m-d');
echo Carbon::createFromFormat('M Y', 'Feb 2024')->startOfMonth()->format('Y-m-d');

Carbon version: 2.72.3 (tested with 3.3 as well)

PHP version: 8.1

I expected to get:

2024-02-01

But I actually get:

2024-03-01

I found how it works and why it happens. When we parse date it set the current date and time to parsed month. Today is 30th, but Feb has only 29, that's why it show me next month. To fix this I used:

echo Carbon::createFromFormat('!M Y', 'Feb 2024')->format('Y-m-d');

But I expect that it should work in the normal way.

Thanks!

kylekatarnls commented 7 months ago

Hello, use Carbon::createFromFormat('!M Y', 'Feb 2024');, see https://www.php.net/manual/en/datetime.createfromformat.php

Duplicates https://github.com/briannesbitt/Carbon/issues/1003#issuecomment-370336838