在 MySQL 中将日期从"dd/mm/yyyy"转换为"yyyymmdd"
mysqlmysqli database
要将日期从"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)