如何在 MySQL 中将 dd/mm/yyyy 字符串转换为 UNIX 时间戳?
在 UNIX_TIMESTAMP() 的帮助下,将 dd/mm/yyyy 字符串转换为 UNIX 时间戳。语法如下所示 −
SELECT UNIX_TIMESTAMP(STR_TO_DATE(yourColumnName,'%d/%m/%Y')) as anyVariableName FROM yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下 −
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 命令在表中插入一些记录。查询如下所示 −
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)
使用 select 语句显示表中的所有记录。查询如下所示 −
mysql> select *from ConvertddmmyyyyInUnixTimeStamp;
以下是输出 −
+----+------------+ | 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)
现在让我们将 dd/mm/yyyy 字符串转换为 UNIX 时间戳
mysql> select unix_timestamp(str_to_date(Created_at,'%d/%m/%Y')) as UnixTimestamp from ConvertddmmyyyyInUnixTimeStamp;
以下是输出
+---------------+ | UnixTimestamp | +---------------+ | 1352485800 | | 1386700200 | | 1355077800 | | 1422642600 | | 1461436200 | | 1505845800 | | 1521052200 | +---------------+ 7 rows in set (0.00 sec)
广告