Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

date

php

For example, I have a time in this format:

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

How do I convert it to :

09:15 16:25 23:25 

Currently my code is :

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

However, it seems there are some easier and more elegant way to do this?

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

How do I fit the above sample in my case? Thanks.

like image 355
user1871516 Avatar asked Jun 06 '13 06:06

user1871516


People also ask

How do I convert 12 hour to 24 hour format?

Changing 12-Hour Time to 24-Hour Time. Use 00:00 to signify midnight in 24-hour time. Rather than using "12:00" twice in a 24-hour period, like in 12-hour time, 24-hour time uses "00:00" for the midnight hour.


2 Answers

Try with this

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

or you can try like this also

echo date("H:i", strtotime("04:25 PM")); 
like image 118
Gautam3164 Avatar answered Oct 07 '22 02:10

Gautam3164


If you use a Datetime format see http://php.net/manual/en/datetime.format.php

You can do this :

$date = new \DateTime(); echo date_format($date, 'Y-m-d H:i:s'); #output: 2012-03-24 17:45:12  echo date_format($date, 'G:ia'); #output: 05:45pm 
like image 43
Babou34090 Avatar answered Oct 07 '22 00:10

Babou34090