如何将 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) -> ); Query OK, 0 rows affected (1.10 sec)
使用 insert 命令向表中插入一些记录。查询如下:-
mysql> insert into VarcharToDate(Created_Time) values('12/1/2016'); Query OK, 1 row affected (0.14 sec) mysql> insert into VarcharToDate(Created_Time) values('14/3/2017'); Query OK, 1 row affected (0.18 sec) mysql> insert into VarcharToDate(Created_Time) values('15/3/2018'); Query OK, 1 row affected (0.21 sec) mysql> insert into VarcharToDate(Created_Time) values('19/5/2011'); Query OK, 1 row affected (0.18 sec) mysql> insert into VarcharToDate(Created_Time) values('19/8/2019'); Query OK, 1 row affected (0.15 sec) mysql> insert into VarcharToDate(Created_Time) values('21/11/2020'); Query OK, 1 row affected (0.23 sec)
使用 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)
广告