简体   繁体   中英

Convert 24 hour format hours into 12 hour format time in php

How can I convert 24 hour format hours into 12 hour format time in php like 1630 should be 4:30 PM.

there are articles to convert 24 hour format time into 12 hour format time like 16:30 into 04:30 PM but I need to convert hours into time.

I am doing it by dividing it by 1200 and get remainder as minute but I hope there is another way to do it using date or time functions.

You can do it like this

<?php
 $date  =  date("Y-m-d 16:30:00");
 echo date("h:i a",strtotime($date));
?>

Live demo : https://eval.in/858486

Or if your time is 1630

$time = 1630;
$time = (int)(1630/100).":".(1630%100);
$date  =  date("Y-m-d $time:00");
echo date("h:i a",strtotime($date));

Live demo : https://eval.in/858559

Update for 3 digits number like 920 or 815

$time = "0920"; // here $time should be string `0` is for other base of number
$last2 = substr($time, -2);
$time = str_replace($last2,":".$last2,$time);
$date  =  date("Y-m-d $time");
echo date("h:i a",strtotime($date));

Live demo : https://eval.in/858555

我认为这对你有用。

date("h:i a",strtotime("1630"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM