MYSQL日期时间到最近一小时 [英] MYSQL Date Time Round To Nearest Hour

查看:330
本文介绍了MYSQL日期时间到最近一小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MySQL数据库中有一个日期时间字段,并希望将结果输出到最接近的小时。

I have a date time field in a MySQL database and wish to output the result to the nearest hour.

2012-04-01 00:00:01 应阅读 2012-04-01 00:00:00

推荐答案

你可以用一些日期算术:

You can do it with some date arithmetic:

SELECT some_columns,
    DATE_ADD(
        DATE_FORMAT(the_date, "%Y-%m-%d %H:00:00"),
        INTERVAL IF(MINUTE(the_date) < 30, 0, 1) HOUR
    ) AS the_rounded_date
FROM your_table

说明:


  • DATE_FORMAT DATE_FORMAT(the_date,%Y-%m-%d%H :00:00)将截断日期缩小到最接近的小时(将分钟和第二部分设置为零)。

  • DATE_FORMAT: DATE_FORMAT(the_date, "%Y-%m-%d %H:00:00") returns the date truncated down to the nearest hour (sets the minute and second parts to zero).

MINUTE MINUTE(the_date)获取日期的分钟值。

MINUTE: MINUTE(the_date) gets the minute value of the date.

IF :这个是有条件的如果参数1中的值为真,则返回参数2,否则返回参数3.所以 IF(MINUTE(the_date)< 30,0,1) 如果分钟值小于30,返回0,否则返回1。这是我们将要使用的 - 这是添加的小时数。

IF: This is a conditional; if the value in parameter 1 is true, then it returns parameter 2, otherwise it returns parameter 3. So IF(MINUTE(the_date) < 30, 0, 1) means "If the minute value is less than 30, return 0, otherwise return 1". This is what we're going to use to round -- it's the number of hours to add back on.

DATE_ADD :这样可以增加一轮的小时数结果。

DATE_ADD: This adds the number of hours for the round into the result.

这篇关于MYSQL日期时间到最近一小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆