如何在 PHP 中将时间从 AM/PM 转换为 24 小时格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16955209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert the time from AM/PM to 24 hour format in PHP?
提问by user1871516
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.
我如何在我的情况下适应上述样本?谢谢。
回答by Gautam3164
Try with this
试试这个
echo date("G:i", strtotime($time));
or you can try like this also
或者你也可以这样尝试
echo date("H:i", strtotime("04:25 PM"));
回答by Babou34090
If you use a Datetime format see http://php.net/manual/en/datetime.format.php
如果您使用日期时间格式,请参阅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
回答by Prolific Solution
You can use this for 24 hour to 12 hour:
您可以在 24 小时到 12 小时内使用它:
echo date("h:i", strtotime($time));
And for vice versa:
反之亦然:
echo date("H:i", strtotime($time));
回答by Bsienn
回答by Viral M
$Hour1 = "09:00 am";
$Hour = date("H:i", strtotime($Hour1));
回答by sumit
We can use Carbon
我们可以用 Carbon
$time = '09:15 PM';
$s=Carbon::parse($time);
echo $military_time =$s->format('G:i');
回答by zioMitch
$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));