將 MySQL 日期格式從 dd.mm.yy 轉換為 YYYY-MM-DD?


使用 MySQL 中的 STR_TO_DATE() 方法進行轉換。以下是語法,其中我們使用了格式說明符。格式說明符以 % 開頭。

SELECT STR_TO_DATE(yourDateColumnName,'%d.%m.%Y') as anyVariableName FROM yourTableName;

為了理解以上語法,我們建立一個表。建立表的查詢如下。

mysql> create table ConvertIntoDateFormat
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> LoginDate varchar(30),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.47 sec)

使用插入命令在表中插入一些記錄。查詢如下 -

mysql> insert into ConvertIntoDateFormat(LoginDate) values('11.01.2019');
Query OK, 1 row affected (0.10 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('10.04.2017');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('21.10.2016');
Query OK, 1 row affected (0.12 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('26.09.2018');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('25.12.2012');
Query OK, 1 row affected (0.17 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 -

mysql> select *from ConvertIntoDateFormat;

以下是輸出。

+----+------------+
| Id | LoginDate  |
+----+------------+
|  1 | 11.01.2019 |
|  2 | 10.04.2017 |
|  3 | 21.10.2016 |
|  4 | 26.09.2018 |
|  5 | 25.12.2012 |
+----+------------+
5 rows in set (0.00 sec)

以下是將日期格式化為 YYYY-MM-DD 的查詢。

mysql> select str_to_date(LoginDate,'%d.%m.%Y') as DateFormat from ConvertIntoDateFormat;

以下是輸出。

+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+
5 rows in set (0.00 sec)

你還可以為此目的使用 DATE_FORMAT() 方法。查詢如下

mysql> select DATE_FORMAT(STR_TO_DATE(LoginDate,'%d.%m.%Y'), '%Y-%m-%d') as DateFormat from
   -> ConvertIntoDateFormat;

以下是輸出 -

+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+
5 rows in set (0.00 sec)

更新時間: 2019 年 7 月 30 日

2 萬 + 瀏覽

開啟您的 職業生涯

完成課程並取得認證

立即開始
廣告
© . All rights reserved.