user1871516
user1871516

Reputation: 1009

How to convert the time from AM/PM to 24 hour format in 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.

Upvotes: 58

Views: 185881

Answers (9)

albin thomas
albin thomas

Reputation: 35

We Can Create AM/PM by Carbon Laravel

Carbon::parse('your Value')->format('g:i A');

Upvotes: -1

Abdul Rehman
Abdul Rehman

Reputation: 1794

PHP 5.3+ solution.

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

Output: 13:00:00

Works great when formatting of date is required. Check This Answer for details.

Upvotes: 10

Saurabh Mani Pandey
Saurabh Mani Pandey

Reputation: 11

$s = '07:05:45PM';
$tarr = explode(':', $s);
if(strpos( $s, 'AM') === false && $tarr[0] !== '12'){
    $tarr[0] = $tarr[0] + 12;
}elseif(strpos( $s, 'PM') === false && $tarr[0] == '12'){
    $tarr[0] = '00';
}
echo preg_replace("/[^0-9 :]/", '', implode(':', $tarr));

Upvotes: 1

Viral M
Viral M

Reputation: 261

$Hour1 = "09:00 am";
$Hour =  date("H:i", strtotime($Hour1));  

Upvotes: 2

sumit
sumit

Reputation: 15464

We can use Carbon

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

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

Upvotes: 4

Michele Carino
Michele Carino

Reputation: 1048

$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[A-Z]+/s', '', implode(':', $chunks));

Upvotes: 0

Prolific Solution
Prolific Solution

Reputation: 93

You can use this for 24 hour to 12 hour:

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

And for vice versa:

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

Upvotes: 8

Babou34090
Babou34090

Reputation: 381

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

Upvotes: 11

GautamD31
GautamD31

Reputation: 28763

Try with this

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

or you can try like this also

echo date("H:i", strtotime("04:25 PM"));

Upvotes: 144

Related Questions