php 如何将日期/时间从 24 小时制转换为 12 小时制 AM/PM?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17098158/
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 do I convert date/time from 24-hour format to 12-hour AM/PM?
提问by Edward
From a data feed I'm getting date and time in this format:
从数据馈送中,我以这种格式获取日期和时间:
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 小时的 AM/PM 没有秒。所以上面的时间是晚上 7:24。日期应保持为 mm/dd/yyyy 格式。在 PHP(不是 MySQL)中有一种优雅的方法可以做到这一点吗?谢谢!
回答by Fabio
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
现场样品
his used for 12 digit time
istands for minutes
sseconds
awill return am or pm (use in uppercase for AM PM)
mis used for months with digits
dis used for days in digit
Yuppercase is used for 4 digit year (use it lowercase for two digit)
h用于 12 位数字时间
i代表分
s秒
a将返回 am 或 pm(用于 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
现场样品
回答by Aowal
You can use date function to format it by using the code below:
您可以使用 date 函数通过使用以下代码对其进行格式化:
echo date("g:i a", strtotime("13:30:30 UTC"));
output: 1:30 pm
输出:下午 1:30
回答by Dexter
Use smaller h
使用更小的 h
// 24 hrs
H:i
// output 14:20
// 12 hrs
h:i
// output 2:20