Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Chuyển DateTime thành chuỗi trong MySQL

Để chuyển giá trị DateTime thành chuỗi trong MySQL, dùng hàm DATE_FORMAT(). Cú pháp:

select date_format(yourColumnName, '%d %m %y') as anyVariableName from yourTableName;

Để hiểu rõ, tạo bảng:

mysql> create table DateAsStringDemo
-> (
-> YourDateTime datetime
-> );
Query OK, 0 rows affected (0.57 sec)

Chèn ngày dùng curdate():

mysql> insert into DateAsStringDemo values(curdate());
Query OK, 1 row affected (0.24 sec)

Hiển thị bản ghi:

mysql> select *from DateAsStringDemo;

Kết quả:

+---------------------+
| YourDateTime        |
+---------------------+
| 2018-11-26 00:00:00 |
+---------------------+
1 row in set (0.00 sec)

Truy vấn chuyển ngày thành chuỗi:

mysql> select date_format(YourDateTime,'%d %m %y') as YourDateAsString from DateAsStringDemo;

Kết quả:

+------------------+
| YourDateAsString |
+------------------+
| 26 11 18         |
+------------------+
1 row in set (0.00 sec)