在MySQL中将varchar转换为日期?
您可以使用date_format()将varchar转换为日期。语法如下-
SELECT DATE_FORMAT(STR_TO_DATE(yourColumnName, 'yourFormatSpecifier'), 'yourDateFormatSpecifier') as anyVariableName from yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table VarcharToDate-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Created_Time varchar(100),
-> PRIMARY KEY(Id)
-> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into VarcharToDate(Created_Time) values('12/1/2016');mysql> insert into VarcharToDate(Created_Time) values('14/3/2017');
mysql> insert into VarcharToDate(Created_Time) values('15/3/2018');
mysql> insert into VarcharToDate(Created_Time) values('19/5/2011');
mysql> insert into
VarcharToDate(Created_Time) values('19/8/2019');
mysql> insert into VarcharToDate(Created_Time) values('21/11/2020');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from VarcharToDate;+----+--------------+
| Id | Created_Time |
+----+--------------+
| 1 | 12/1/2016 |
| 2 | 14/3/2017 |
| 3 | 15/3/2018 |
| 4 | 19/5/2011 |
| 5 | 19/8/2019 |
| 6 | 21/11/2020 |
+----+--------------+
6 rows in set (0.00 sec)
这是将varchar转换为日期的查询。首先,您需要使用str_to_date()函数将其转换为日期。之后,使用date_format()给出实际日期-
mysql> select date_format(str_to_date(Created_Time, '%d/%m/%Y'), '%Y-%m-%d') as Date from VarcharToDate;
以下是输出-
+------------+| Date |
+------------+
| 2016-01-12 |
| 2017-03-14 |
| 2018-03-15 |
| 2011-05-19 |
| 2019-08-19 |
| 2020-11-21 |
+------------+
6 rows in set (0.00 sec)
以上是 在MySQL中将varchar转换为日期? 的全部内容, 来源链接: utcz.com/z/338512.html