【问题标题】:Why does the CAST() function return the wrong date?为什么 CAST() 函数返回错误的日期?
【发布时间】:2016-09-12 02:08:24
【问题描述】:

我正在尝试从时间戳字段中获取日期部分。 我使用了这个 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

我们如何解决这个问题?

【问题讨论】:

    标签: mysql sql date


    【解决方案1】:

    这不是问题!它只是设置了错误的 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]>
    

    【讨论】:

      【解决方案2】:

      我建议您使用 DATE_FORMAT 函数而不是 CAST,因为您正在格式化日期

      SELECT `timestamp`, DATE_FORMAT(`timestamp`, '%Y-%m-%d) as my_date from messages
      

      还要注意 CAST 和 DATE 函数都在内部调用 Item_date_typecast 函数,所以它们之间没有这样的区别。

      【讨论】:

        【解决方案3】:

        试试这个

        select timestamp, cast(timestamp as date format 'yyyymmddhhmmss') as date from messages
        

        【讨论】:

        • 得到 SQL 错误:#1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 1 行的消息 LIMIT 0, 25' 附近使用 'format 'yyyymmddhhmmss') 作为日期
        【解决方案4】:

        使用日期不转换,因为不是转换而是格式

        select timestamp, date(timestamp) as my_date from messages
        

        【讨论】:

        • 很好的答案。谢谢它就像魅力一样。但是 DATE_FORMAT() 函数也会产生错误的格式。这是为什么呢?
        • Date() 提取有效日期时间的日期部分 ,,, Date_format 更改日期的方面...您使用什么格式..?
        • 我用过%d %M, %Y
        • 我重复定义“提取日期或日期时间表达式的日期部分”,因此给定有效的日期时间提取日期部分..不涉及转换、格式或设置时间设置..跨度>
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-12
        • 2011-05-18
        • 1970-01-01
        • 2016-05-18
        • 1970-01-01
        • 2021-01-18
        相关资源
        最近更新 更多