我正在尝试从时间戳字段获取日期部分。 我使用了这个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
。
我们如何解决这个问题?
答案 0 :(得分:7)
这不是问题!!!它只设置了错误的time_zone。见样本
获取当前时间
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]>
答案 1 :(得分:5)
使用未投出日期,因为不是投射而是格式
select timestamp, date(timestamp) as my_date from messages
答案 2 :(得分:5)
我建议您使用DATE_FORMAT函数而不是CAST,因为您要格式化日期
SELECT `timestamp`, DATE_FORMAT(`timestamp`, '%Y-%m-%d) as my_date from messages
另请注意,CAST和DATE函数都在内部调用Item_date_typecast函数,因此它们之间没有这样的区别。
答案 3 :(得分:0)
试试这个
select timestamp, cast(timestamp as date format 'yyyymmddhhmmss') as date from messages