รูปแบบวันที่ใน MySQL: %M vs %b
%M = ชื่อเดือนเต็ม (January, February, ...)
%b = ชื่อเดือนย่อ 3 ตัวอักษร (Jan, Feb, Mar, ...)
ไวยากรณ์
SELECT DATE_FORMAT(yourDateColumn, '%d-%b-%y') AS formatted_date FROM yourTableName;
ตัวอย่างการใช้งาน
สร้างตาราง:
CREATE TABLE DateFormatMonthDemo (
Id INT NOT NULL AUTO_INCREMENT,
ShippingDate DATE,
PRIMARY KEY(Id)
);
เพิ่มข้อมูล:
INSERT INTO DateFormatMonthDemo(ShippingDate) VALUES('2019-05-21');
INSERT INTO DateFormatMonthDemo(ShippingDate) VALUES('2015-05-23');
INSERT INTO DateFormatMonthDemo(ShippingDate) VALUES('2019-11-01');
INSERT INTO DateFormatMonthDemo(ShippingDate) VALUES('2017-12-24');
INSERT INTO DateFormatMonthDemo(ShippingDate) VALUES('2016-01-13');
INSERT INTO DateFormatMonthDemo(ShippingDate) VALUES('2015-02-22');
แสดงชื่อเดือนย่อ (%b):
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 |
+-----------+
ตารางรูปแบบวันที่ที่เกี่ยวข้องกับเดือน
| Format | ชื่อ | ตัวอย่าง |
|---|---|---|
| %M | ชื่อเดือนเต็ม | January, February, March |
| %b | ชื่อเดือนย่อ (3 ตัวอักษร) | Jan, Feb, Mar |
| %m | เดือนตัวเลข (01-12) | 01, 02, 03 |
| %c | เดือนตัวเลข (1-12) | 1, 2, 3 |
รูปแบบวันที่ยอดนิยม
-- Thai format: 21 มกราคม 2562
SELECT DATE_FORMAT(date_col, '%d %M %Y'); -- ต้องตั้ง lc_time_names = 'th_TH'
-- ISO 8601: 2019-01-21
SELECT DATE_FORMAT(date_col, '%Y-%m-%d');
-- US format: 01/21/2019
SELECT DATE_FORMAT(date_col, '%m/%d/%Y');
-- Short: 21-Jan-19
SELECT DATE_FORMAT(date_col, '%d-%b-%y');
ตั้งค่าภาษาไทยสำหรับ %M
SET lc_time_names = 'th_TH';
SELECT DATE_FORMAT('2019-01-21', '%d %M %Y'); -- 21 มกราคม 2019