2

我想将 YYYY-MM-DD 列转换为 unix 时间戳。类似于这个问题:MySQL - Convert MM/DD/YY to Unix timestamp

MySQL 似乎没有将 '2012-05-10' 的值转换为正确的 unixtime。这是失败的建议功能: SELECT UNIX_TIMESTAMP(CAST(dateid AS DATE)) AS unixtime

4

2 回答 2

1

你用的是什么版本MySQL?正如 MySQL 5.5.27 在 SQLFiddle 中测试的那样,这两个查询有效

SELECT UNIX_TIMESTAMP(CAST('2012-05-10 00:00:00' AS DATETIME)) As UnixTime;
SELECT UNIX_TIMESTAMP(CAST('2012-05-10' AS DATE))  As UnixTime;

SQLFiddle 演示

于 2012-09-25T02:58:56.160 回答
1

我不确定您到底遇到了什么问题,但以下工作正常:

CREATE TABLE ex (dt VARCHAR(20));
INSERT INTO ex SET dt = '2012-05-10';

SELECT
UNIX_TIMESTAMP('2012-05-10') ex1,
UNIX_TIMESTAMP(dt)  ex2,
UNIX_TIMESTAMP(CAST('2012-05-10' AS DATE)) ex3,
UNIX_TIMESTAMP(CAST(dt AS DATE)) ex4
FROM ex;

返回:

+------------+------------+------------+------------+
| ex1        | ex2        | ex3        | ex4        |
+------------+------------+------------+------------+
| 1336633200 | 1336633200 | 1336633200 | 1336633200 |
+------------+------------+------------+------------+

CAST()如您所见,如果字符串为YYYY-MM-DDor形式,则不需要YYYY-MM-DD HH:MM:SS,因为 MySQL 会将此格式的字符串隐式转换为DATEs。

http://sqlfiddle.com/#!2/1a215/3

于 2012-09-25T02:59:00.253 回答