briannesbitt / Carbon

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

Failed to parse time dd/mm/yyyy using parseFromLocale with Portuguese #3029

Closed FranciscoCaldeira closed 6 months ago

FranciscoCaldeira commented 6 months ago

Hello,

I encountered an issue with the following code:

echo Carbon::parseFromLocale('31/05/2022', 'pt');

Carbon version: * 3.4.0

PHP version: 8.3.6

I expected to get:

2022/05/31 00:00:00

But I actually get:

Carbon\Exceptions\InvalidFormatException with message 'Could not parse '31/05/2022': Failed to parse time string (31/05/2022) at position 0 (3): Unexpected character'
   null

Thanks!

kylekatarnls commented 6 months ago

Hello,

parseFromLocale is only able to translate day names or month names in the given string from the given locale to English, then it will try to use the result into new Carbon($englishString).

You can either give your format explicitly:

echo Carbon::createFromFormat('d/m/Y', '31/05/2022');

Or use the L ISO-format which is for instance DD/MM/YYY in Portuguese but MM/DD/YYYY in US English:

echo Carbon::createFromLocaleIsoFormat('L', 'pt', '31/05/2022');

Thanks,