我想转换这种格式的日期时间“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
andTIMESTAMP
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
orYYMMDDHHMMSS
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/