Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

php

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!

like image 849
Edward Avatar asked Jun 13 '13 22:06

Edward


People also ask

How do you convert 24 hour to AM PM?

"AM" stands for "ante meridiem" which means "before noon" while PM stands for "post meridiem" which means "after noon." Include the signifier "AM" for times between 1:00 and 11:59. Since 24-hour times moves from 00:00 (midnight) to 1:00, all you have to do is add "AM" to the time from 1:00 up until 11:59.

How do I convert 24 hour time in Excel?

Right click the selected cells and then click Format Cells, or press Ctrl + 1. This will open the Format Cells dialog box. On the Number tab, under Category, select Custom, and type one of the following time formats in the Type box: Over 24 hours: [h]:mm:ss or [h]:mm.


1 Answers

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

like image 70
Fabio Avatar answered Sep 18 '22 22:09

Fabio