如何将PHP中的时间从AM / PM转换为24小时格式?

2022-08-30 10:26:55

例如,我有一个时间以这种格式:

eg. 

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

如何将其转换为:

09:15
16:25
23:25

目前我的代码是:

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

但是,似乎有一些更简单,更优雅的方法来做到这一点?

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

我如何将上述样品适合我的情况?谢谢。


答案 1

试试这个

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

或者您也可以尝试这样

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

答案 2

如果使用日期时间格式,请参阅 http://php.net/manual/en/datetime.format.php

你可以这样做:

$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

推荐