使用 Carbon 我得到 "textual month could not be found" 错误

Using Carbon I got "textual month could not be found" error

在我的 Laravel 5.8 应用程序中,我将日期转换为字符串格式,例如 02 May, 2019 使用 Carbon 计算日期。我试了一下 :

setlocale(LC_TIME, 'en');
$filter_check_in_datepicker_till = Carbon::createFromFormat( 'dd MMMM YYY', $filter_check_in_datepicker_till )->locale('en_EN');;

但出现错误:

"message": "Unexpected data found.\nA textual month could not be found\nData missing",

哪种方法正确?

谢谢!

The Carbon docs 说:

createFromFormat() is mostly a wrapper for the base php function DateTime::createFromFormat.

从文档中看并不完全清楚,但这意味着传递给 createFromFormat() 的 $format 参数是 DateTime 格式, 不是 碳格式。因此,您应该使用 d, M Y(检查 DateTime format reference)而不是 dd MMMM YYY

\Carbon\Carbon::createFromFormat('d, M Y', '02, May 2019');
// returns 2019-05-02 12:48:26

作为参考,您的 Carbon 格式存在多个问题,因此即使 createFromFormat 采用 Carbon 格式字符串,您所拥有的也无法正常工作。检查 Carbon format reference:

  • dd其实就是"Minified day name (from Su to Sa), transatable"。您真的想要 DD 作为一个月中的 zero-padded 天;

  • 您使用的日期格式包含一个逗号,但您的格式字符串缺少该逗号;

  • YYY 实际上不是有效的 Carbon 格式字符串。您真的想要 YYYY 作为 4 位数年份;