How to round a DateTime in MySQL?

前端 未结 6 1262
孤城傲影
孤城傲影 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:41

    Here is another variation based on a solution from this thread.

    SELECT DATE_ADD(
               DATE_FORMAT(time, "%Y-%m-%d %H:00:00"),
               INTERVAL FLOOR(MINUTE(time)/5)*5 MINUTE
           );
    

    This solution, unlike ones that use FROM_UNIXTIME, will give the expected value for datetimes that fall within daylight saving time (DST) transitions. (Compare for example 2012-11-03 2:14:00)

    Edit - After some quick benchmarking, however, Ollie's first solution appears to perform faster than this. But I still recommend against the FROM_UNIXTIME method.

提交回复
热议问题