在Laravel/OctoberCMS中将法语日期字符串转为日期对象
Hey there! Let's get that date conversion sorted out for you. The issue you're hitting is because the format string you're using doesn't match the structure of your input date, plus Carbon needs to recognize the French month and day abbreviations to parse it correctly.
Here's what's going wrong: You tried using Y-m-d H:i:s which expects a date like 2018-04-26 10:25:00, but your input is a French-formatted date (jeu. 26 avril 2018 10:25). Carbon can't map those two mismatched formats, hence the "Unexpected data found" error.
Fix Steps:
- Set Carbon to use French locale so it understands French day/month names like "jeu." (short for jeudi) and "avril".
- Use the correct format string that perfectly matches your input's structure.
- Explicitly set the timezone to
Africa/Tunisduring date creation (or adjust it afterward if needed).
Working Code Example:
// First, set Carbon's locale to French to recognize French date terms Carbon\Carbon::setLocale('fr'); // Your input date string $inputDate = 'jeu. 26 avril 2018 10:25'; // Create the Carbon object with the matching format string // Format breakdown: // D = Abbreviated day name (e.g., "jeu." for jeudi) // j = Day of the month without leading zeros (26) // F = Full month name (e.g., "avril") // Y = 4-digit year (2018) // H:i = 24-hour time with minutes (10:25) $carbonDate = Carbon\Carbon::createFromFormat('D j F Y H:i', $inputDate, 'Africa/Tunis'); // If you need to output the exact structure you showed: $result = [ 'date' => $carbonDate->format('Y-m-d H:i:s.u'), // u adds microseconds 'timezone_type' => 3, // Type 3 represents a timezone identifier (like Africa/Tunis) 'timezone' => $carbonDate->getTimezone()->getName() ]; print_r($result);
Quick Notes:
- Ensure the
intlPHP extension is installed on your server—Carbon relies on it to handle locale-specific date formats. - If you're working in a Laravel project, you can set the default locale in
config/app.phpinstead of callingsetLocale()manually.
This should give you the date object with the correct timezone and formatted string you need!
内容的提问来源于stack exchange,提问作者Taha Azzabi
相关产品推荐
相关产品推荐

