如何在PHP中将`June, 18 2021 21:33`转换为`2021-06-18 21:33:00`?
First, let's break down why you're hitting that parse error: Carbon's parse() method struggles with the comma after the month name in your input string (June, 18 2021 21:33). Auto-detecting date formats can be finicky with non-standard separators like that comma. The fix is to explicitly define the input format instead of letting Carbon guess.
Using Carbon (Recommended if you're already using it)
Here's the corrected code that will work perfectly:
$send_time = "June, 18 2021 21:33"; // Define the exact format of your input string to avoid parsing ambiguity $date = Carbon::createFromFormat('F, d Y H:i', $send_time); // Format to your desired output (use H for 24-hour time, not h) echo $date->format('Y-m-d H:i:s');
Quick breakdown of the format codes:
F= Full month name (matches "June"),= Literal comma from your inputd= Two-digit day (matches "18")Y= Four-digit year (matches "2021")H= 24-hour format hour (matches "21")i= Two-digit minutes (matches "33")
Note: I swapped h for H in the output format because h is for 12-hour time (which would turn 21 into 09), while H preserves the 24-hour value you need.
Using Native PHP DateTime (No Carbon Required)
If you don't want to rely on Carbon, PHP's built-in DateTime class works the same way:
$send_time = "June, 18 2021 21:33"; $date = DateTime::createFromFormat('F, d Y H:i', $send_time); echo $date->format('Y-m-d H:i:s');
This will output exactly what you need: 2021-06-18 21:33:00.
Why your original code failed
The parse() method tries to auto-detect date patterns, but the unexpected comma after "June" breaks its ability to recognize the string as a valid date. By specifying the input format explicitly, we remove all ambiguity and ensure the date is parsed correctly.
内容的提问来源于stack exchange,提问作者Qwerty

