如何使用 FORMATDATE() 方法在 MySQL SELECT * 查询中设置日期格式?
在 MySQL 中使用 DATE_FORMAT(),而不是 FORMATDATE() 来设置日期格式。正确的语法如下所示 −
SE LECT *, DATE_FORMAT(yourDateCoumnName,’yourFormat’) as anyAliasName FROM yourTableName
为了理解上述语法,我们创建一个表。创建表的查询如下 −
mysql> create table DateFormatDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(10), -> UserLoginDate date -> ); Query OK, 0 rows affected (0.94 sec)
使用插入命令在表中插入一些记录。查询如下 −
mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Mike',curdate()); Query OK, 1 row affected (0.21 sec) mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Sam','2018-05-09'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Carol','2016-01-15'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Bob','2015-12-31'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('David','2012-08-19'); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from DateFormatDemo;
输出如下 −
+----+----------+---------------+ | Id | UserName | UserLoginDate | +----+----------+---------------+ | 1 | Mike | 2019-02-06 | | 2 | Sam | 2018-05-09 | | 3 | Carol | 2016-01-15 | | 4 | Bob | 2015-12-31 | | 5 | David | 2012-08-19 | +----+----------+---------------+ 5 rows in set (0.00 sec)
让我们使用 DATE_FORMAT() 和 SELECT * 设置日期格式。查询如下 −
mysql> select *,DATE_FORMAT(UserLoginDate,'%d-%m-%Y') as NewFormatOfDate from DateFormatDemo;
输出如下 −
+----+----------+---------------+-----------------+ | Id | UserName | UserLoginDate | NewFormatOfDate | +----+----------+---------------+-----------------+ | 1 | Mike | 2019-02-06 | 06-02-2019 | | 2 | Sam | 2018-05-09 | 09-05-2018 | | 3 | Carol | 2016-01-15 | 15-01-2016 | | 4 | Bob | 2015-12-31 | 31-12-2015 | | 5 | David | 2012-08-19 | 19-08-2012 | +----+----------+---------------+-----------------+ 5 rows in set (0.00 sec)
广告