I have a DATETIME field in mySQL (fromStamp) with a valid date/time stamp in it.
I need to be able to round the minutes UP to the next 6 minute interval. Seconds should be ignored or treated as :00
So, if my DATETIME is 2013-01-31 13:07:17 I need the result to be 2013-01-31 13:12:00
EXCEPT for times between :00 and :06 and :31 and :36 those need to be rounded DOWN.
:00-06 round DOWN to 00
:07-12 round UP to 12
:13-18 round UP to 18
:19-24 round UP to 24
:24-30 round UP to 30
:31-36 round DOWN to 30
:37-42 round UP to 42
:43-48 round UP to 48
:49-54 round UP to 54
:55-00 round UP to 00
I found a reasonable way to selectively round down using:
SELECT
fromStamp,
CONCAT(DATE_FORMAT(`fromStamp`, '%Y-%m-%d'), ' ',
SEC_TO_TIME((TIME_TO_SEC(`fromStamp`) DIV 360) * 360))
FROM `table`
WHERE (
DATE_FORMAT(`fromStamp`, '%i') BETWEEN 0 AND 6
OR DATE_FORMAT(`fromStamp`, '%i') BETWEEN 31 AND 36
);
Is there a good way of rounding everything else up to the next 6 minute interval?
(I feel like I’m missing something simple)
UPDATE
So I’m going with @mellamokb’s solution but his comment regard seconds is right, it does come into play.
A DATETIME of 2013-01-22 12:24:13 rounds UP to 12:30 which is not what is needed so I’ll first do:
UPDATE table SET fromStamp = CONCAT(DATE_FORMAT(fromStamp, '%Y-%m-%d %h:%i'), ':00');
to get rid of the seconds then his query which gets exactly what I’m looking for.
Rounding up is very similar logic, except you add
1to shift to the next nearest6-minuteinterval. I’ve also subtracted1fromTIME_TO_SECas a correcting factor, otherwise borderline values such as06:00get shifted up the next 6-minute interval, i.e.,12:00.To combine the two, use a
CASEstatement to control which form of rounding is used per record:(DEMO)