php - 为什么 PHP 中的日期时间到时间戳转换不起作用?

标签 php mysql datetime timestamp

我想转换这种格式的日期时间“31-12-2018 19:30 hs”。从阿根廷到 UTC 时间戳,我使用以下代码:

$clean_date = substr($date, 0, -4);
$dt = new DateTime($clean_date, new DateTimeZone('America/Argentina/Buenos_Aires'));
$dt->setTimeZone(new DateTimeZone('UTC'));
$timestamp = $dt->getTimestamp();

但是它不起作用,在数据库中记录是“0000-00-00 00:00:00”,但是如果我回显 $dt,直到完美工作并显示 UTC 中的日期时间。

有人可以帮我吗? 谢谢。

最佳答案

这与 PHP 无关。您只是在 MySQL 中使用了不正确的日期文字格式。每the docs :

MySQL recognizes DATETIME and TIMESTAMP values in these formats:

  • As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts.

  • As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date.

  • As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date.

1546335960 可能是最后一种情况,但数字作为日期没有意义,因为 1546 年没有 33 个月。

更糟糕的是,许多 MySQL 服务器默认配置为让此类错误溜走:

mysql> CREATE TABLE test (
    ->     foo TIMESTAMP
    -> );
Query OK, 0 rows affected (0.74 sec)

mysql> SET @@SESSION.sql_mode = '';
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO test (foo) VALUES (1546335960);
Query OK, 1 row affected, 1 warning (0.39 sec)

mysql> SHOW WARNINGS;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'foo' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM test;
+---------------------+
| foo                 |
+---------------------+
| 0000-00-00 00:00:00 |
+---------------------+
1 row in set (0.00 sec)

如您所见,您仅收到警告(您需要明确阅读)和数据损坏。

如果您将应用配置为使用严格模式,您将及时收到正确的错误消息:

mysql> SET @@SESSION.sql_mode = 'TRADITIONAL,NO_AUTO_VALUE_ON_ZERO';
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO test (foo) VALUES (1546335960);
ERROR 1292 (22007): Incorrect datetime value: '1546335960' for column 'foo' at row 1
mysql>

请注意 timestamp只是一个通用的英语单词:

A digital record of the time of occurrence of a particular event.

它不一定是 Unix time 的同义词.

关于php - 为什么 PHP 中的日期时间到时间戳转换不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53994279/

相关文章:

php - CodeIgniter Active Record 一次删除多条记录

php - 数据库结构跟踪用户是否打开特定内容的最佳实践?

c# - 法国应该使用哪个时区来支持新旧夏令时调整?

Python Django 名称错误 : name 'datetime' is not defined

php - mysqli_insert_id() 需要 1 个参数,0 在 CodeIgniter 中给出

php - 如何去除NBSP?

php - INSERT IGNORE 可以返回附加值吗?

php - 为什么我在远程服务器上运行 Zend Framework 2 应用程序时收到错误 : table doesn't exist,?

mysql - Codeigniter,Active Record 不接受 WEEK 参数

Android:以人类可读的格式显示剩余时间