Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

Conversion of Mysql date format (DD-MM-YYYY TO YYYY-MM-DD)

I have three column mysql table ID (int) Date (Varchar) (data in dd-mm-yyyy) Logdate (Date) (Currently empty)

Is there any query which can fetch date and update the Logdate with mysql date format (yyyy-mm-dd)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the STR_TO_DATE function to convert the string to a Date value. You have to specify the format of the date string you provided. In your case it would be '%d-%m-%Y'. For testing purposes you can run the following queries to check if it works:

mysql> EXPLAIN Dummy;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| ID      | int(11)     | YES  |     | NULL    |       |
| oldDate | varchar(50) | YES  |     | NULL    |       |
| logdate | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM Dummy;
+------+------------+------------+
| ID   | oldDate    | logdate    |
+------+------------+------------+
|    1 | 24-12-2019 | 2000-01-01 |
|    1 | 04-09-2017 | 2000-01-01 |
|    1 | 21-02-2019 | 2000-01-01 |
+------+------------+------------+
3 rows in set (0.00 sec)

mysql> SELECT oldDate, STR_TO_DATE(oldDate, '%d-%m-%Y') FROM Dummy;
+------------+----------------------------------+
| oldDate    | STR_TO_DATE(oldDate, '%d-%m-%Y') |
+------------+----------------------------------+
| 24-12-2019 | 2019-12-24                       |
| 04-09-2017 | 2017-09-04                       |
| 21-02-2019 | 2019-02-21                       |
+------------+----------------------------------+
3 rows in set (0.00 sec)

You can then run an UPDATE query to update the values in the logdate column.

mysql> UPDATE Dummy SET logdate = STR_TO_DATE(oldDate, '%d-%m-%Y');
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> SELECT * FROM Dummy;
+------+------------+------------+
| ID   | oldDate    | logdate    |
+------+------------+------------+
|    1 | 24-12-2019 | 2019-12-24 |
|    1 | 04-09-2017 | 2017-09-04 |
|    1 | 21-02-2019 | 2019-02-21 |
+------+------------+------------+
3 rows in set (0.00 sec)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...