在MySQL中将日期从”dd/mm/yyyy”转换为”yyyymmdd”
要将日期从”dd/mm/yyyy”转换为”yyyymmdd”,可以使用date_format()方法。让我们先创建一个表-
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Admissiondate varchar(200)
);
Query OK, 0 rows affected (0.54 sec)
使用insert命令在表中插入一些记录-
mysql> insert into DemoTable(Admissiondate) values('21/10/2014');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(Admissiondate) values('01/12/2016');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Admissiondate) values('31/01/2017');
Query OK, 1 row affected (0.14 sec)
使用select语句从表中显示所有记录的查询如下-
mysql> select *from DemoTable;
这将产生以下输出-
+----+---------------+
| Id | Admissiondate |
+----+---------------+
| 1 | 21/10/2014 |
| 2 | 01/12/2016 |
| 3 | 31/01/2017 |
+----+---------------+
3 rows in set (0.00 sec)
将日期从”dd/mm/yyyy”转换为”yyyymmdd”的查询如下-
mysql> select date_format(str_to_date(Admissiondate,'%d/%m/%Y'),'%Y%m%d') from DemoTable;
这将产生以下输出-
+-------------------------------------------------------------+
| date_format(str_to_date(Admissiondate,'%d/%m/%Y'),'%Y%m%d') |
+-------------------------------------------------------------+
| 20141021 |
| 20161201 |
| 20170131 |
+-------------------------------------------------------------+
3 rows in set (0.00 sec)
阅读更多:MySQL 教程