简体   繁体   中英

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?

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:

InvalidArgumentException in Carbon.php line 414: Unexpected data found. Data missing

You can always use PHP's strtotime() function and then manipulate the structure using date() as seen below.

$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. 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:

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

The first argument is the format of the date in your string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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