You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中将`June, 18 2021 21:33`转换为`2021-06-18 21:33:00`?

Solution to Convert Date Format in PHP (Carbon & Native DateTime)

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.

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 input
  • d = 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:42:48