[php] How do I convert date/time from 24-hour format to 12-hour AM/PM?

From a data feed I'm getting date and time in this format:

19:24:15 06/13/2013

I need to have it converted to be in 12-hour AM/PM without the seconds. So the above time would be 7:24 PM. The date should remain in mm/dd/yyyy format. Is there an elegant way to do this in PHP (not MySQL)? Thanks!

This question is related to php date

The answer is


I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample


Use smaller h

// 24 hrs 
H:i 
// output 14:20

// 12 hrs 
h:i 
// output 2:20

You can use date function to format it by using the code below:

echo date("g:i a", strtotime("13:30:30 UTC"));

output: 1:30 pm