MySQL DATE_FORMAT '%M' 用于短月份?

mysqlmysqli database

%M 日期格式不用于显示短月份,例如 Jan 表示一月、Feb 表示二月等。您需要使用 DATE_FORMAT() 函数和 %b 格式来显示短月份。语法如下:

SELECT DATE_FORMAT(yourColumnName, '%d-%b-%y') AS anyVariableName FROM yourTableName;

为了理解上述语法,让我们创建一个表。创建表的查询如下:

mysql> create table DateFormatMonthDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> ShippingDate date,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.63 sec)

使用 insert 命令在表中插入一些记录。插入记录的查询如下:

mysql> insert into DateFormatMonthDemo(ShippingDate) values('2019-05-21');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DateFormatMonthDemo(ShippingDate) values('2015-05-23');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DateFormatMonthDemo(ShippingDate) values('2019-11-01');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DateFormatMonthDemo(ShippingDate) values('2017-12-24');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DateFormatMonthDemo(ShippingDate) values('2016-01-13');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DateFormatMonthDemo(ShippingDate) values('2015-02-22');
Query OK, 1 row affected (0.19 sec)

使用 select 语句显示表中的所有记录。查询如下:

mysql> select *from DateFormatMonthDemo;
+----+--------------+
| Id | ShippingDate |
+----+--------------+
|  1 | 2019-05-21   |
|  2 | 2015-05-23   |
|  3 | 2019-11-01   |
|  4 | 2017-12-24   |
|  5 | 2016-01-13   |
|  6 | 2015-02-22   |
+----+--------------+
6 rows in set (0.00 sec)

以下是显示短月份名称的查询:

mysql> select DATE_FORMAT(ShippingDate, '%d-%b-%y') AS DateDemo from DateFormatMonthDemo;

输出结果如下:

+-----------+
| DateDemo  |
+-----------+
| 21-May-19 |
| 23-May-15 |
| 01-Nov-19 |
| 24-Dec-17 |
| 13-Jan-16 |
| 22-Feb-15 |
+-----------+
6 rows in set (0.04 sec)

相关文章