在PHP中将时间格式从上午9:00更改为09:00 am

在PHP中将时间格式从上午9:00更改为09:00 am

问题描述:

Iam having variable with value 9:30 am - 12:00 pm i.e

       $val=$shift (o/p 9:30 am - 12:00pm)

I want to convert it to 09:30 am - 12:00pm, i mean i need to add 0 infront of number if time having one digit

Iam变量值为9:30 am - 12:00 pm,即 p> $ val = $ shift(o / p 9:30 am - 12:00 pm) code> pre>

我想将其转换为09:30 am - 中午12点,我的意思是如果时间有一位数,我需要在数字前面添加0 p> div>

Assuming you are saving your time in your database as a string as 9:30 am - 12:00pm you can just split them. Then format each data.

$val= "9:30 am - 12:00pm";
$splittedString = explode('-', $val);

$time1 = date('h:ia',strtotime($splittedString[0]));
$time2 = date('h:ia',strtotime($splittedString[1]));

echo $time1." - ".$time2;

If you are using date function then you can format time using h.

For example

echo date('h:ia'); // output 09:50am

See Referance

If you have values from DataBase as you mentioned in comment then you need to apply PHP's built-in function strtotime() before formatting the time.

For Example

echo date( 'h:ia', strtotime('9:30 am') ); // output 09:50am

Try

echo date('h:ia',strtotime("9:30 am"))." - ".date('h:ia',strtotime("12:00pm"));