我写了一个函数来重新排列数据库中存储的日期格式,从 d-m-y
到 y-d-m
。带有原始日期的原始字符串与插入查询一起正确存储,但格式化的字符串不是。
表结构:
+-------+------+
| Field | Type |
+-------+------+
| id | INT()|
+-------+------+
| date1 | DATE |
+-------+------+
| date2 | DATE |
+-------+------+
PHP:
<?php
$db = new mysqli("localhost","root","","test");
function date2Store($date) {
$dateFormat = DateTime::createFromFormat('d-m-y',$date);
return $dateFormat->format('y-d-m');
}
$dateRaw = "22-01-17";
$dateFormatted = date2Store($dateRaw);
echo $dateFormatted; // Checking how the string looks
$query = "INSERT INTO dateTest(date1,date2) VALUES ('$dateFormatted','$dateRaw')";
echo $query; // Checking how the query looks
$db->query($query);
?>
结果是:
+----+------------+------------+
| id | date1 | date2 |
+----+------------+------------+
| 1 | 0000-00-00 | 2022-01-17 |
+----+------------+------------+
$query 输出:
INSERT INTO dateTest(date1,date2) VALUES ('17-22-01','22-01-17')
我检查过两者都是字符串,查询看起来是正确的。为什么他们存储不同?
最佳答案
17-22-01
不是有效日期,因此 - 根据您的 MySQL 服务器的配置 - 它不会存储在带有 DATE
的字段中类型。
如果你想存储你的源格式,它不是有效的 mysql 日期格式,可以使用另一种字段类型,p.e. varchar
.
看看here into the MySQL manual发现 MySql 允许的日期格式 - 因此可以在您的 INSERT
-statement 中使用:
MySQL recognizes
DATE
values in these formats:
As a string in either '
YYYY-MM-DD
' or 'YY-MM-DD
' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31
', '2012/12/31
', '2012^12^31
', and '2012@12@31
' are equivalent.As a string with no delimiters in either '
YYYYMMDD
' or 'YYMMDD
' format, provided that the string makes sense as a date. For example, '20070523
' and '070523
' are interpreted as '2007-05-23
', but '071332
' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00
'.As a number in either
YYYYMMDD
orYYMMDD
format, provided that the number makes sense as a date. For example,19830905
and830905
are interpreted as '1983-09-05
'.
关于php - 插入 DATE 意外行为。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41791310/