How to round a DateTime in MySQL?

前端 未结 6 1230
孤城傲影
孤城傲影 2020-12-21 17:48

I want to discretize the DateTime with the resolution of 5 minutes. I did it in C#, but how to convert the following code to MySQL?

DateTime Floor(DateTime d         


        
6条回答
  •  隐瞒了意图╮
    2020-12-21 18:39

    Another alternative:

    to get the nearest hour:

    TIMESTAMPADD(MINUTE,
        ROUND(TIMESTAMPDIFF(MINUTE,CURDATE(),timestamp_column_name)/60)*60,
        CURDATE())
    

    Instead of CURDATE() you can use an arbitrary date, for example '2000-01-01' Not sure if there could be problems using CURDATE() if the system date changes between the two calls to the function, don't know if Mysql would call both at the same time.

    changing 60 by 15 would get the nearest 15 minutes interval, using SECOND you can get the nearest desired second interval, etc.

    To get the previous hour use TRUNCATE() or FLOOR() instead of ROUND().

    Hope this helps.

提交回复
热议问题