Display Time Format with AM and PM in Carbon using Laravel

Last updated on January 13, 2023

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

Conclusion

This article demonstrates displaying the time format with AM and PM. For that we used format() method from Carbon class.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Laravel, Time,