Convert hour to PM and AM with Carbon

Sredny M Casanova picture Sredny M Casanova · Dec 11, 2015 · Viewed 25.6k times · Source

I have a timestamp in PHP, so I'm using Carbon extension to manage everything that is related with date, time,etc. Now I have for example a hour 23:00 or 20:00 with this extension how I can convert that to AM and PM format?

Answer

Thomas Kim picture Thomas Kim · Dec 11, 2015

I'm not sure if there is a out-of-the-box helper method for this, but you could always use the format method, which defers to the base class method DateTime::format().

Example:

$now = Carbon::now();
echo $now->format('g:i A');

This will echo out something like 5:17 PM.

The g, i, and A can seem random, but the list of parameters can be found here: http://php.net/manual/en/function.date.php

g: 12-hour format of an hour without leading zeros

i: Minutes with leading zeros

A: Uppercase Ante meridiem and Post meridiem