How to insert a date in the format dd-mm-yy in MySQL?

泪湿孤枕 提交于 2020-02-04 20:42:29

问题


I have to insert dates in MySQL with the format dd-mm-yy.

I know that if I change the date format to yy-mm-dd it will work, but my client wants it in the format dd-mm-yy, and the default format of a MySQL date is 0000-00-00.


回答1:


As Honeyboy said in the comments, you can use the SELECT_TO_DATE function with the format string "%d-%m-%y". You can test it like this:

CREATE DATABASE test;
USE TEST;
CREATE TABLE test (date1 date);
INSERT INTO test (date1) VALUES (STR_TO_DATE("03-04-15","%d-%m-%y"));

then with

SELECT * FROM test;

you obtain:

+------------+
| date1      |
+------------+
| 2015-04-03 |
+------------+

If you use PHP, you can then make a prepared statement such as:

$stmt = $conn->prepare("INSERT INTO test (date1) VALUES (STR_TO_DATE(?,'%d-%m-%y'));");
$stmt->bind_param("s", $client_date);
$stmt->execute();

Same principle with other languages.



来源:https://stackoverflow.com/questions/48947472/how-to-insert-a-date-in-the-format-dd-mm-yy-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!