MySQL将YYYY-MM-DD转换为unix时间戳

时间:2012-09-25 02:51:22

标签: mysql datetime unix-timestamp

我想将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

2 个答案:

答案 0 :(得分:1)

您使用的MySQL版本是什么?正如SQLFiddle中的MySQL 5.5.27测试的那样,这两个查询工作

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 Demo

答案 1 :(得分: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-DD,则无需YYYY-MM-DD HH:MM:SS,因为MySQL会将此格式的字符串隐式转换为{{1} }第

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