我在MySQL中有一个日期时间列。
如何将其转换为显示为mm/dd/yy H:M (AM/PM)使用PHP?
我在MySQL中有一个日期时间列。
如何将其转换为显示为mm/dd/yy H:M (AM/PM)使用PHP?
当前回答
将从MySQL检索到的日期转换为所要求的格式(mm/dd/yy H:M (AM/PM)):
// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM
请参考PHP日期格式选项来调整格式。
其他回答
要在PHP中正确格式化DateTime对象以存储在MySQL中,请使用MySQL使用的标准化格式,即ISO 8601。
PHP从5.1.1版本开始就将这种格式存储为常量,我强烈建议使用这种格式,而不是每次都手动输入字符串。
$dtNow = new DateTime();
$mysqlDateTime = $dtNow->format(DateTime::ISO8601);
这个和其他PHP DateTime常量的列表可以在http://php.net/manual/en/class.datetime.php#datetime.constants.types上找到
使用date函数:
<?php
echo date("m/d/y g:i (A)", $DB_Date_Field);
?>
将从MySQL检索到的日期转换为所要求的格式(mm/dd/yy H:M (AM/PM)):
// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM
请参考PHP日期格式选项来调整格式。
如果您正在使用PHP 5,也可以尝试一下
$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");
更简单的方法是直接在MySQL查询中格式化日期,而不是PHP。请参阅MySQL手册中的DATE_FORMAT条目。
如果更愿意在PHP中完成,则需要date函数,但必须首先将数据库值转换为时间戳。