How to convert time from AM / PM to 24-hour format in PHP?

For example, I have time in this format

eg. 09:15 AM 04:25 PM 11:25 AM 

How to convert it to

 09:15 16:25 23:25 

My current code is:

 $format_time = str_replace(" AM", "", $time, $count); if ($count === 0){ $format_time = strstr($time, ' PM', true); $format_time = ...... } 

However, there seems to be a simpler and more elegant way to do this?

 $time = '23:45'; echo date('g:i a', strtotime($time)); 

How to match the above sample in my case? Thanks

+27
string date php
Jun 06 '13 at 6:33
source share
6 answers

Try with this

 echo date("G:i", strtotime($time)); 

and you can try it also

 echo date("H:i", strtotime("04:25 PM")); 
+61
Jun 06 '13 at 6:35
source share

If you are using the Datetime format, see http://php.net/manual/en/datetime.format.php

You can do it:

 $date = new \DateTime(); echo date_format($date, 'Ymd H:i:s'); #output: 2012-03-24 17:45:12 echo date_format($date, 'G:ia'); #output: 05:45pm 
+6
Jun 06 '13 at 6:37
source share

You can use this for 24 hours to 12 hours:

 echo date("h:i", strtotime($time)); 

And for the opposite:

 echo date("h:i", strtotime($time)); 
+5
Mar 28 '16 at 7:01
source share
 $time = '09:15 AM'; $chunks = explode(':', $time); if (strpos( $time, 'AM') === false && $chunks[0] !== '12') { $chunks[0] = $chunks[0] + 12; } else if (strpos( $time, 'PM') === false && $chunks[0] == '12') { $chunks[0] = '00'; } echo preg_replace('/\s[AZ]+/s', '', implode(':', $chunks)); 
0
Oct 09 '16 at 21:26
source share

PHP 5.3+.

 $new_time = DateTime::createFromFormat('h:i A', '01:00 PM'); $time_24 = $new_time->format('H:i:s'); 

Outpit: 13:00:00

Works great with format dates. Mark This Answer.

0
Mar 30 '17 at 11:03
source share

We can use Carbon

  $time = '09:15 PM'; $s=Carbon::parse($time); echo $military_time =$s->format('G:i'); 

http://carbon.nesbot.com/docs/

0
Apr 10 '17 at 6:05
source share



All Articles