我认为将日期时间值保存在类型字段中DATETIME
是一种自然的方式。
根据我自己对当前 PHP 应用程序的经验,只有read
/write
与此信息相关的操作可能会出现问题。
DATETIME
正确执行整个过程的一种可能的解决方案(假设您使用数据类型)可能是以下方法:
读取 PHP 使用的 DATETIME 值
- 从数据库中获取
DATETIME
字段,将查询中的字段转换为字符串表示形式,方法'2011-10-02T23:25:42Z'
是使用带有格式化字符串的DATE_FORMAT
MySQL 函数( DATE_FORMAT 上的文档)'%Y-%m-%dT%H:%i:%sZ'
- 以这种特定格式读取获取的列值,并在 PHP 中将其从字符串转换为对 PHP 有效的真实日期时间表示(例如给定格式化字符串的
DateTime
类对象和DateTime::createFromFormat
静态方法(并转义以避免将它们视为格式化指令)(docs for方法)。'Y-m-d\TH:i:s\Z'
T
Z
- 将转换后的值用作具有所有适用逻辑的真实日期时间值,例如真实日期比较(不是文本比较)等。
将 PHP 日期时间写入 MySQL 数据库
- 使用类对象的方法,使用与格式化字符串(文档)之前相同的方法,将 PHP
DateTime
类对象转换为我们的 ISO 8601 UTC 格式字符串表示。DateTime
format
'Y-m-d\TH:i:s\Z'
- 使用这种准备好的字符串作为 MySQL 函数的参数(带有格式化字符串)对数据库信息执行
INSERT
/操作,该函数将其转换为真实的数据库值(STR_TO_DATE 上的文档)。UPDATE
STR_TO_DATE
'%Y-%m-%dT%H:%i:%sZ'
DATETIME
PHP 中的示例代码
请在下面找到使用 PDO 对象的这种方法的示例草稿:
$db = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// run the query aquring 1 example row with DATETIME data
// converted with MySQL DATE_FORMAT function to its string representation
// in the chosen format (in our case: ISO 8601 / UTC)
$stmt = $db->query("SELECT DATE_FORMAT(dt_column, '%Y-%m-%dT%H:%i:%sZ') AS formatted_dt_col"
." FROM your_table LIMIT 1");
if($stmt !== FALSE) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// convert the acquired string representation from DB
// (i.e. '2011-10-02T23:25:42Z' )
// to PHP DateTime object which has all the logic of date-time manipulation:
$dateTimeObject = DateTime::createFromFormat('Y-m-d\TH:i:s\Z', $row['formatted_dt_col']);
// the following should print i.e. 2011-10-02T23:25:42Z
echo $dateTimeObject->format('Y-m-d\TH:i:s\Z');
// now let's write PHP DateTime class object '$dateTimeObject'
// back to the database
$stmtInsertDT = $db->prepare("INSERT INTO your_table(dt_column) "
. " VALUES ( STR_TO_DATE(:par_formatted_dt_column, '%Y-%m-%dT%H:%i:%sZ') )");
$dtAsTextForInsert = $dateTimeObject->format('Y-m-d\TH:i:s\Z');
// convert '$dateTimeObject' to its ISO 8601 / UTC text represantation
// in order to be able to put in in the query using PDO text parameter
$stmtInsertDT->bindParam(':par_formatted_dt_column', $dtAsTextForInsert, PDO::PARAM_STR);
$stmtInsertDT->execute();
// So the real insert query being perform would be i.e.:
/*
INSERT INTO your_table(dt_column)
VALUES ( STR_TO_DATE('2011-10-02T23:25:42Z', '%Y-%m-%dT%H:%i:%sZ') )
*/
}
}
catch(\PDOException $pexc) {
// serve PDOException
}
catch(\Exception $exc) {
// in case of no-PDOException, serve general exception
}
这种方法对我在 PHP 和 MySQL 数据库之间操作日期时间值有很大帮助。
我希望它也会对您有所帮助。