[英]How to convert the time from AM/PM to 24 hour format in PHP?
例如,我有一个这种格式的时间:
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));
我如何在我的情况下安装上述样本? 谢谢。
试试这个
echo date("G:i", strtotime($time));
或者你也可以这样尝试
echo date("H:i", strtotime("04:25 PM"));
如果您使用日期时间格式,请参阅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
PHP 5.3+ 解决方案。
$new_time = DateTime::createFromFormat('h:i A', '01:00 PM');
$time_24 = $new_time->format('H:i:s');
输出:13:00:00
当需要格式化日期时效果很好。 检查此答案以获取详细信息。
您可以在 24 小时到 12 小时内使用它:
echo date("h:i", strtotime($time));
反之亦然:
echo date("H:i", strtotime($time));
我们可以使用Carbon
$time = '09:15 PM';
$s=Carbon::parse($time);
echo $military_time =$s->format('G:i');
$Hour1 = "09:00 am";
$Hour = date("H:i", strtotime($Hour1));
$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));
$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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.