我正在尝试从时间戳字段中获取日期部分。 我使用了这个 SQL 查询:
select timestamp, CAST(timestamp as date) as date from messages
我得到了以下结果:
--------------------------------------------
| timestamp | date |
--------------------------------------------
| 2016-05-15 10:22:54 | 2016-05-16 |
--------------------------------------------
如上所示,生成的日期字段返回错误的日期2016-05-16
,而原始日期为2016-05-15
。
我们如何解决这个问题?
最佳答案
这不是问题!!!它只设置了错误的时区。看样本
获取当前时区
SHOW GLOBAL VARIABLES LIKE 'time_zone'; -- systemwide setting
SHOW VARIABLES LIKE 'time_zone'; -- session setting
样本
MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+---------------------+-----------------+
| t | CAST(t as date) |
+---------------------+-----------------+
| 2016-05-15 20:22:54 | 2016-05-15 |
+---------------------+-----------------+
1 row in set (0.00 sec)
MariaDB [mysql]> SET time_zone ='-12:00';
Query OK, 0 rows affected (0.00 sec)
MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+---------------------+-----------------+
| t | CAST(t as date) |
+---------------------+-----------------+
| 2016-05-14 20:22:54 | 2016-05-14 |
+---------------------+-----------------+
1 row in set (0.00 sec)
MariaDB [mysql]>
关于mysql - 为什么 CAST() 函数返回错误的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251313/