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:

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?

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:

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:

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!

Facebook Comments