如何在MySQL中以dd-mm-yy格式插入日期? [英] How to insert a date in the format dd-mm-yy in MySQL?
问题描述
我必须在MySQL中以 dd-mm-yy
格式插入日期。
I have to insert dates in MySQL with the format dd-mm-yy
.
我知道如果我将日期格式更改为 yy-mm-dd
可以使用,但是我的客户希望日期格式为 dd-mm-yy
,MySQL日期的默认格式为 0000-00-00
。
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
.
推荐答案
正如Honeyboy在评论中所说,您可以使用 SELECT_TO_DATE
函数,其格式字符串为%d-%m-%y
。您可以像这样进行测试:
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"));
然后与
SELECT * FROM test;
您获得:
+------------+
| date1 |
+------------+
| 2015-04-03 |
+------------+
如果使用PHP,然后可以编写一条准备好的语句,例如:
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.
这篇关于如何在MySQL中以dd-mm-yy格式插入日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!