MYSQL Date Time Round To Nearest Hour

前端 未结 8 533
孤独总比滥情好
孤独总比滥情好 2020-12-09 14:52

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

e.g. 2012-04-01 00:00:01 should read 2012-04-01 00

8条回答
  •  猫巷女王i
    2020-12-09 15:10

    soul's first solution truncates instead of rounding and the second solution doesn't work with Daylight Savings cases such as:

    select FROM_UNIXTIME(UNIX_TIMESTAMP('2012-03-11 2:14:00') - MOD(UNIX_TIMESTAMP('2012-03-11 2:14:00'),300));
    

    Here is an alternate method (1):

    DATE_ADD(
        tick,
        INTERVAL (IF((MINUTE(tick)*60)+SECOND(tick) < 1800, 0, 3600) - (MINUTE(tick)*60)+SECOND(tick)) SECOND
    )
    

    If you don't need to worry about seconds you can simplify it like this (2):

    DATE_ADD(
        tick,
        INTERVAL (IF(MINUTE(tick) < 30, 0, 60) - MINUTE(tick)) MINUTE
    )
    

    Or if you prefer to truncate instead of round, here is simpler version of soul's method (3):

    DATE_SUB(tick, INTERVAL MINUTE(tick)*60+SECOND(tick) SECOND)
    

    EDIT: I profiled some of these queries on my local machine and found that for 100,000 rows the average times were as follows:

    • soul's UNIXTIME method: 0.0423 ms (fast, but doesn't work with DST)
    • My method 3: 0.1255 ms
    • My method 2: 0.1289 ms
    • Ben Lee's DATE_FORMAT method: 0.1495 ms
    • My method 1: 0.1506 ms

提交回复
热议问题