Select timestamp as date string in MySQL?

MySQLMySQLi Database

To select timestamp as date string in MySQL, the syntax is as follows −

select FROM_UNIXTIME(yourColumnName, '%Y-%m-%d %H:%i:%s') from yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table select_timestampDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ArrivalDateTime int
   -> );
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into select_timestampDemo(ArrivalDateTime) values(1546499730);
Query OK, 1 row affected (0.18 sec)
mysql> insert into select_timestampDemo(ArrivalDateTime) values(1546210820);
Query OK, 1 row affected (0.23 sec)
mysql> insert into select_timestampDemo(ArrivalDateTime) values(1496363157);
Query OK, 1 row affected (0.29 sec)

Now you can display all records from the table using select statement. The query is as follows −

mysql> select *from select_timestampDemo;

Here is the output −

+----+-----------------+
| Id | ArrivalDateTime |
+----+-----------------+
| 1  | 1546499730      |
| 2  | 1546210820      |
| 3  | 1496363157      |
+----+-----------------+
3 rows in set (0.00 sec)

The following is the query to select timestamp as a date string −

mysql> select FROM_UNIXTIME(ArrivalDateTime, '%Y-%m-%d %H:%i:%s') from select_timestampDemo;

Here is the output −

+-----------------------------------------------------+
| FROM_UNIXTIME(ArrivalDateTime, '%Y-%m-%d %H:%i:%s') |
+-----------------------------------------------------+
| 2019-01-03 12:45:30                                 |
| 2018-12-31 04:30:20                                 |
| 2017-06-02 05:55:57                                 |
+-----------------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 01-Apr-2019 12:19:40
Advertisements