49

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!

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
Edward
  • 9,430
  • 19
  • 48
  • 71

3 Answers3

150

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

Fabio
  • 23,183
  • 12
  • 55
  • 64
13

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

Max Gaurav
  • 1,835
  • 2
  • 13
  • 26
Aowal
  • 131
  • 1
  • 2
13

Use smaller h

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

# 12 hrs 
h:i 
// output 2:20
Dexter
  • 7,911
  • 4
  • 41
  • 40