将MySQL时间戳转换为更易读的格式

时间:2012-03-15 13:51:18

标签: php mysql

基本上我希望将时间戳字段从:2012-03-14 23:14:58格式转换为(更具可读性)23:14 pm March 15, 2012

我已经度过了这个tutorial,但是我无法理解它。我已经包含了我当前用于将MySQL数据库数据解析为Android应用程序的PHP脚本。

<?php
$con = mysql_connect("*******", "*******", "*******");

if(!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("bluebase", $con);


$q=mysql_query("SELECT * from Comments where Category = 'General' ORDER BY Timestamp DESC");

while($e=mysql_fetch_assoc($q)) 

        $output['General'][]=$e;

    print(json_encode($output));

mysql_close();

&GT;

4 个答案:

答案 0 :(得分:4)

您可以选择几条路径。我一直在做的是将时间作为Unix时间戳存储在数据库中,因为它很容易从那里转换。如果您的数据库中已有数据并且更改它已太晚(或者您有其他原因在数据库中以该格式表示日期),那么您需要将时间转换为unix时间戳,以便它可用于PHP日期函数:

while($e=mysql_fetch_assoc($q)) {
    $e['Timestamp'] = date('h:i a F d, Y', strtotime($e['Timestamp']));
    $output['General'][]=$e;
}

...用您重新格式化的时间戳覆盖Timestamp字段。

答案 1 :(得分:0)

这就是诀窍:

<?php
  echo date('H:i a F j, Y', strtotime($timestamp));
?>

答案 2 :(得分:0)

date('h:i a F d, Y', strtotime('2012-03-14 23:14:58'));

请注意,'d'是带有领先零的日期。

并且'h'是12小时格式,因为您要显示AM / PM

如果您不想要前导零,请在数字日使用'j',在12小时格式小时编号使用'g'。

答案 3 :(得分:0)

您可以根据需要使用date()格式化日期。只需使用

date('H:i a F d, Y', strtotime($timestamp));

虽然米洛在问题评论中指出,但没有理由使用24小时格式和上午/下午。

相关问题