在将字符串转换为日期的STR_TO_DATE()方法中指定格式说明符。以下是语法-
select STR_TO_DATE(yourColumnName,'yourFormatSpecifier') from yourTableName;
让我们首先创建一个表-
mysql> create table DemoTable -> ( -> AdmissionDate varchar(100) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('01-12-2019'); mysql> insert into DemoTable values('15-06-2019'); mysql> insert into DemoTable values('21-01-2016');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
这将产生以下输出-
+---------------+ | AdmissionDate | +---------------+ | 01-12-2019 | | 15-06-2019 | | 21-01-2016 | +---------------+ 3 rows in set (0.00 sec)
以下是对STR_TO_DATE()的查询。在这里,我们还设置了格式说明符-
mysql> select STR_TO_DATE(AdmissionDate,'%d-%m-%Y') from DemoTable;
输出结果
这将产生以下输出-
+---------------------------------------+ | STR_TO_DATE(AdmissionDate,'%d-%m-%Y') | +---------------------------------------+ | 2019-12-01 | | 2019-06-15 | | 2016-01-21 | +---------------------------------------+ 3 rows in set (0.04 sec)