简体   繁体   English

如何在 Laravel 中格式化单独的日期和时间变量

[英]How can I format separate date and time variables in Laravel

I have a $date and $time fields that are stored in my db, I would like to know how can I format these fields to display them in a different format?我有一个 $date 和 $time 字段存储在我的数据库中,我想知道如何格式化这些字段以以不同的格式显示它们?

eg例如

2010-05-09 -> 9th May 2010

and

13:00:00 -> 1:00PM

I have tried to use carbon but it returns the following error:我曾尝试使用 carbon,但它返回以下错误:

InvalidArgumentException in Carbon.php line 414: Unexpected data found. Carbon.php 第 414 行中的 InvalidArgumentException:发现意外数据。 Data missing数据缺失

You can always use PHP's strtotime() function and then manipulate the structure using date() as seen below.您始终可以使用 PHP 的strtotime()函数,然后使用date()操作结构,如下所示。

$dateString = strtotime("2010-05-09");
$date = date("jS F, Y" ,$dateString);
echo $date;

$timeString = strtotime("13:00:00");
$time = date("g:i A" ,$timeString);
echo $time;

FWIW, I didn't realize you said specifically in Laravel. FWIW,我没有意识到你在 Laravel 中专门说的。 But I typed it all out, so figured I'd share anyways.但是我把它全部打出来了,所以我想无论如何我都会分享。 Carbon (as mentioned above) may handle this in a similar fashion.碳(如上所述)可以以类似的方式处理这个问题。

You have to use the createFromFormat method:您必须使用createFromFormat方法:

$time = Carbon::createFromFormat('H:i:s', '13:00:00')->format('g:iA');

The first argument is the format of the date in your string.第一个参数是字符串中日期的格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM