如何将日期/时间从24小时格式转换为12小时上午/下午?

时间:2022-07-30 01:52:52

From a data feed I'm getting date and time in this format:

从数据Feed我得到这种格式的日期和时间:

19:24:15 06/13/2013

I need to have it converted to be in 12-hour AM/PM without the seconds. So the above time would be 7:24 PM. The date should remain in mm/dd/yyyy format. Is there an elegant way to do this in PHP (not MySQL)? Thanks!

我需要把它转换成12小时上午/下午没有秒。所以上面的时间是晚上7:24。日期应保持为mm / dd / yyyy格式。在PHP(而不是MySQL)中有一种优雅的方法吗?谢谢!

2 个解决方案

#1


80  

I think you can use date() function to achive this

我认为你可以使用date()函数来实现这个目标

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

这将输出

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

h用于12位数时间i代表分钟s秒a将返回上午或下午(使用大写字母表示AM PM)m用于数月,数字d用于天数字数字Y大写用于4位数年份(使用小写两位数)

Updated

更新

This is with DateTime

这与DateTime有关

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

#2


1  

You can use date function to format it by using the code below:

您可以使用日期函数使用以下代码对其进行格式化:

echo date("g:i a", strtotime("13:30:30 UTC"));

output: 1:30 pm

输出:下午1:30

#1


80  

I think you can use date() function to achive this

我认为你可以使用date()函数来实现这个目标

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

这将输出

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

h用于12位数时间i代表分钟s秒a将返回上午或下午(使用大写字母表示AM PM)m用于数月,数字d用于天数字数字Y大写用于4位数年份(使用小写两位数)

Updated

更新

This is with DateTime

这与DateTime有关

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

#2


1  

You can use date function to format it by using the code below:

您可以使用日期函数使用以下代码对其进行格式化:

echo date("g:i a", strtotime("13:30:30 UTC"));

output: 1:30 pm

输出:下午1:30