PHP: 如何整理日期时间信息?

PHP: Ways to tidy up date time information?

我的一个 PHP/Laravel 程序从一个 API 端点收集时间日期,在我称之为 $time 的变量中。它以以下格式呈现:

2018-12-10T22:14:04Z

我想把它整理成更典型的东西,比如以下任何一个:

"10-12-2018" "22:14, 10-12-2018" "10-12-2018, 22:14:04"

我是 PHP 这方面的新手,所以我一直在研究不同的方法来做到这一点。虽然我遇到了 some questions similar to mine, and I've found the documentation for tools like createfromformat and strtotime,但从我读到的内容来看,我认为它们无法解决我正在使用的精确格式。

PHP 中是否有任何内置方法可以让我做到这一点?或者人们可能会建议我尝试根据需要重新格式化日期的任何代码行?对此的任何帮助将不胜感激

您可以将存储的日期时间字符串传递给 DateTime() 对象并自由控制其格式 (及更多)。例如:

$time = '2018-12-10T22:14:04Z';

$dateTimeObject = new \DateTime($time);
echo $dateTimeObject->format('Y-m-d H:i:s'); // will output: 2018-12-10 22:14:04

我建议你使用 Carbon 包来转换日期和日期时间,它真的很棒。

通常 Laravel 已经包含 Carbon,但如果您不知何故没有它,请使用此安装:

composer require nesbot/carbon

现在如果你想在你的控制器中使用它,你需要导入:

use Carbon\Carbon;

而且您应该可以这样做:

Carbon::createFromFormat('d/m/Y', $yourcurrentformat);

你应该阅读 docs