Retrieve time from MySQL as HH:MM format?

MySQLMySQLi Database

To retrieve time as HH:MM format, use the DATE_FORMAT() function. To understand the function and retrieve time, let us create a table.

The query to create a table is as follows

mysql> create table retrieveTimeDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserArrivalTime datetime
   -> );
Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2013-01-21 13:45:34');
Query OK, 1 row affected (0.16 sec)
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2014-11-25 11:40:56');
Query OK, 1 row affected (0.11 sec)
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2016-10-27 17:30:40');
Query OK, 1 row affected (0.12 sec)
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2017-02-21 18:03:06');
Query OK, 1 row affected (0.19 sec)
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2018-04-24 22:30:32');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from retrieveTimeDemo;

The following is the output

+--------+---------------------+
| UserId | UserArrivalTime     |
+--------+---------------------+
| 1      | 2013-01-21 13:45:34 |
| 2      | 2014-11-25 11:40:56 |
| 3      | 2016-10-27 17:30:40 |
| 4      | 2017-02-21 18:03:06 |
| 5      | 2018-04-24 22:30:32 |
+--------+---------------------+
5 rows in set (0.00 sec)

Here is the query to retrieve time from MySQL as HH:MM format

mysql> select date_format(UserArrivalTime,'%H:%i') from retrieveTimeDemo;

The following is the output

+--------------------------------------+
| date_format(UserArrivalTime,'%H:%i') |
+--------------------------------------+
| 13:45                                |
| 11:40                                |
| 17:30                                |
| 18:03                                |
| 22:30                                |
+--------------------------------------+
5 rows in set (0.00 sec)
raja
Published on 29-Mar-2019 10:36:52

Advertisements