Convert dd/mm/yyyy string to Unix timestamp in MySQL?

MySQLMySQLi Database

Convert dd/mm/yyyy string to Unix timestamp with the help of UNIX_TIMESTAMP(). The syntax is as follows −

SELECT UNIX_TIMESTAMP(STR_TO_DATE(yourColumnName,'%d/%m/%Y')) as anyVariableName FROM yourTableName;

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

mysql> create table ConvertddmmyyyyInUnixTimeStamp
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Created_at varchar(30),
   -> PRIMARY KEY(Id)
   -> );
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 ConvertddmmyyyyInUnixTimeStamp(Created_at) values('10/11/2012');
Query OK, 1 row affected (0.21 sec)

mysql> insert into ConvertddmmyyyyInUnixTimeStamp(Created_at) values('11/12/2013');
Query OK, 1 row affected (0.23 sec)

mysql> insert into ConvertddmmyyyyInUnixTimeStamp(Created_at) values('10/12/2012');
Query OK, 1 row affected (0.12 sec)

mysql> insert into ConvertddmmyyyyInUnixTimeStamp(Created_at) values('31/01/2015');
Query OK, 1 row affected (0.19 sec)

mysql> insert into ConvertddmmyyyyInUnixTimeStamp(Created_at) values('24/04/2016');
Query OK, 1 row affected (0.21 sec)

mysql> insert into ConvertddmmyyyyInUnixTimeStamp(Created_at) values('20/09/2017');
Query OK, 1 row affected (0.26 sec)

mysql> insert into ConvertddmmyyyyInUnixTimeStamp(Created_at) values('15/03/2018');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from ConvertddmmyyyyInUnixTimeStamp;

The following is the output −

+----+------------+
| Id | Created_at |
+----+------------+
| 1 | 10/11/2012 |
| 2 | 11/12/2013 |
| 3 | 10/12/2012 |
| 4 | 31/01/2015 |
| 5 | 24/04/2016 |
| 6 | 20/09/2017 |
| 7 | 15/03/2018 |
+----+------------+
7 rows in set (0.00 sec)

Let us now convert dd/mm/yyyy string to UNIX timestamp:

mysql> select unix_timestamp(str_to_date(Created_at,'%d/%m/%Y')) as UnixTimestamp from ConvertddmmyyyyInUnixTimeStamp;

The following is the output:

+---------------+
| UnixTimestamp |
+---------------+
| 1352485800    |
| 1386700200    |
| 1355077800    |
| 1422642600    |
| 1461436200    |
| 1505845800    |
| 1521052200    |
+---------------+
7 rows in set (0.00 sec)
raja
Published on 01-Feb-2019 15:36:31
Advertisements