2011-12-20 51 views
1

我在php中使用mysql。我如何只显示小时和分钟?

这是我的函数,它返回json格式的结果。这个功能的

function getTiming($placeId) { 

    $sql = "SELECT * from place_timing where placeId='$placeId'"; 

    $result = mysql_query($sql) or die ("Query error: " . mysql_error()); 

    $records = array(); 

    if (mysql_num_rows($result)==0) 

    { 

     echo '['.json_encode(array('placeId' => 0)).']'; 
     //this is for null result 

    } 

    else 

    { 

     while($row = mysql_fetch_assoc($result)) 

     { 

     $records[] = $row; 

     } 


     echo json_encode($records); //this concerts in json 

    } 

} 

输出是这样的: -

[{"placeId":"31","sun_open_time":"00:00:00","sun_close_time":"00:00:00","mon_open_time":"00:00:00","mon_close_time":"23:00:00","tue_open_time":"00:00:00","tue_close_time":"00:00:00"}] 

但我想只显示小时:分钟。意味着我不想显示秒。

请建议我如何更改我的上述功能,以便我只能显示小时:分钟。

预先感谢您。

+2

这属于[“我如何格式化MySQL日期时间”]的标准类别(http://stackoverflow.com/search?q=%5Bmysql%5D+%5Bphp%5D+change+time+format) ,例如[更改MySQL PHP中日期和时间字段的显示格式](http://stackoverflow.com/questions/2411970/change-display-format-of-date-and-time-field-in-mysql-php ) – deceze 2011-12-20 09:32:54

回答

3

有很多方法可以做到这一点,“最干净的”将是在SELECT子句中指定列,并像DATE_FORMAT()那样传递日期,如下所示:DATE_FORMAT(sun_open_time, '%H:%i')

+0

这不会工作,如果sun_open_time只有像hh:mm:ss这样的时间格式的数据。 – Kammy 2011-12-20 09:56:11

+0

它将适用于TIMESTAMP(这是最常用的类型)和DATE_TIME;我不确定它不适用于TIME,但即使如此,您也可以切换到TIME_FORMAT()。 – Viruzzo 2011-12-20 10:33:29

1

调整你的查询来选择实际的领域,而不是*,然后在时间字段使用TIME_FORMAT(),如:

SELECT TIME_FORMAT(`sun_open_time`, '%H %i') AS `opentime`; 

这将直接从该查询返回所需的值没有任何PHP黑客。

0

看来你的表place_timing(sun_open_time,sun_close_time等等)的字段只有hh:mm:ss格式化时间。所以你必须使用MySql的SUBSTRING()函数。

所以你查询可能如下。

$ SQL =“SELECT SUBSTRING(sun_open_time,1,5), SUBSTRING(sun_close_time,1,5),SUBSTRING(mon_open_time,1,5), SUBSTRING(mon_close_time,1,5), SUBSTRING(tue_open_time,1,5),SUBSTRING(tue_close_time,1,5)从 place_timing其中placeId ='$ placeId'“;