简体   繁体   English

在PHP Select语句中将MYSQL时间从HH:MM:SS转换为HH:MM

[英]Convert MYSQL time from HH:MM:SS to HH:MM during PHP Select statement

I am using a PHP Select statement to pull data from MySQL. 我正在使用PHP Select语句从MySQL中提取数据。 The eventTime field is stored as TIME in the schema as HH:MM:SS but I only want HH:MM. eventTime字段在架构中以TIME的形式存储为HH:MM:SS,但我只需要HH:MM。 I have tried using TIME_FORMAT(eventTime, '%H:%i') in the select statement but it does not work. 我尝试在select语句中使用TIME_FORMAT(eventTime,'%H:%i'),但它不起作用。 Any ideas? 有任何想法吗? I have even tried to convert the variable in PHP but I am stumped. 我什至试图在PHP中转换变量,但是我很困惑。 Please help me identify what I'm missing. 请帮助我确定我所缺少的。

$query="SELECT id,eventDate,eventTime, eventName FROM specialevents ORDER BY eventDate,eventTime ASC";

$result=$mysqliConnection->query($query,MYSQLI_STORE_RESULT);

while($row =$result->fetch_object())
  {


     $id=$row->id;
     $eventDate=$row->eventDate;
     $eventTime=$row->eventTime;
     $eventName=$row->eventName;
     $reportTime=$row->reportTime;

 echo '<tr>’; 
 echo '<td class="tdId"><input type="text" class="tbId" value="' . $id . '"/></td>’; 
 echo '<td class="tdEventDate"><input type="text" class="tbEventDate" value="' . $eventDate . '"/></td>’; 
 echo '<td class="tdEventTime"><input type="text" class="tbEventTime" value="' . $eventTime . '"/></td>’; 
 echo '<td class="tdEventName"><input type="text" class="tbEventName" value=" ' . $eventTime . '"/></td>’; 
 echo '<td class="tdReportTime"><input type="text" class="tbReportTime" value=" ' . $reportTime . '"/></td>';   

}

You shouldn't be storing date and time separately if they refer to the same entity. 如果日期和时间是指同一实体,则不应将它们分开存储。 However, you can use MySQL's TIME_FORMAT() function to format your time: 但是,您可以使用MySQL的TIME_FORMAT()函数来格式化时间:

 TIME_FORMAT(date,format) 

Formats the date value according to the format string. 根据格式字符串格式化日期值。

$query="SELECT id, eventDate, TIME_FORMAT(eventTime, '%H:%i') AS eventTime, eventName 
FROM specialevents 
ORDER BY eventDate, eventTime ASC";

You can use the specifiers from DATE_FORMAT to format as you wish. 您可以根据需要使用DATE_FORMAT的说明符进行格式化。

Also, the ASC sort order is default and can be omitted from your query. 同样, ASC排序顺序是默认的,可以从查询中省略。

在PHP中(不确定MySQL),您可以执行以下操作:

$formatted_date = date('H:i:s', strtotime($mysql_timedate));

Assuming you have column of type time The Php approach as follows : 假设您具有类型为time 的Php列, 如下所示:

$new_time = date('H:i', strtotime($mysql_timedate)); // mysql_timedate is the row containg time form the db and outout is hour:mins

Mysql approach : mysql的方法:

$sql = "SELECT DATE_FORMAT(column name here, '%H:%i') FROM table name"; // output hour:mins

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM