Display time format with AM and PM in Carbon using Laravel

Laravel uses a carbon package that deals with date and time. To display time with AM and PM we can use the format() method with characters that display time accordingly. To begin with, let’s import the carbon class into the controller.

use Carbon\Carbon;

After importing the class we can get the current date and time using the now() method.

// current date and time
$currentDateTime = Carbon::now();
// Output: 2022-11-17 18:13:00.872700

As $current DateTime has a date object it can access the format() method. Let’s use format() method to display AM or PM along with time.

// display time with AM or PM
$currentDateTime->format('g:i A');
// Output: 6:26 PM

As you can see the format() method returns time along with string type and Post meridiem because at the time of writing this article it was evening time. We passed a few characters into format() method which are following

  • g : returns 12-hour time format, for example, 1 to 12
  • i: returns minutes, for example, 00 to 59
  • A : returns Ante meridiem and Post meridiem in uppercase, for example, AM and PM