PHP: Convert 24 hour time to 12 hour time with AM/PM.

This is a PHP tutorial on how to convert a standard 24 hour date and time into a 12 hour time. Furthermore, I will also show you how to add the AM and PM period abbreviations.

Take the following example:

//Example Y-m-d H:i:s date string.
$date = '2019-02-15 16:56:01';

//12 hour format with uppercase AM/PM
echo date("g:iA", strtotime($date));

In the code above, we converted a standard datetime string into a 12 hour time with an uppercase AM/PM abbreviation. We did this by using PHP’s inbuilt date and strtotime functions. The character “g” tells the date function that we want a 12-hour format of an hour without leading zeros. The uppercase “A” character is for AM / PM.

But what if you want a lowercase am / pm abbreviation?

//Example Y-m-d H:i:s date string.
$date = '2019-02-15 16:56:01';

//12 hour format with lowercase AM/PM
echo date("g:ia", strtotime($date));

As you can see, it’s pretty much the same as the first example. The only difference is that we used a lowercase a instead of an uppercase A in the format parameter.

Note that we removed the time in seconds from both examples as seconds are usually not typically displayed in this format.

Using the DateTime object.

If you prefer using PHP’s DateTime object, then you can use the following code:

//Create a DateTime object using the original
//datetime string.
$date = new DateTime('2019-02-15 16:56:01');

//Convert it into the 12 hour time using the format method.
echo $date->format('g:ia') ;

The above piece of code will print out: 4:56pm

Leading zeros.

If you do want to display leading zeros in your time format, then you should use the character h instead of g.

An example:

//Create a DateTime object using the original
//datetime string.
$date = new DateTime('2019-01-14 09:12:10');

//Print out the 12 hour time using the format method.
echo $date->format('h:ia') ;

If you run the PHP code above, you should see that it prints out: 09:12am

That’s pretty much all there is to it! Hopefully, this guide solved your problem!