5

I need a fast implementation of a "Date jump" algorithm that is to be included in an event management system.
An event is triggered and sets a date (in a synchronized method) to the next 10th minute.

For instance

  Event occurs at "2010-01-05 13:10:12" and sets the 
  next date to be "2010-01-05 13:20:00"

and if an event occurs exactly (supposedly) at a 10th minute, the next one must be set

  Event occurs at "2010-01-05 13:30:00" and sets the 
  next date to be "2010-01-05 13:40:00"

(unlikely since the date goes down to the 1/1000th of a second, but just in case...).

My first idea would be to get the current Date() and work directly with the ms from the getTime() method, via integer (long) division, like ((time / 10mn)+1)*10mn.

Since it has to be fast, and also reliable, I thought I'll ask my fellow OSers prior to the implementation.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100

2 Answers2

10

You can use / adapt my answer to a very similar question:

How to round time to the nearest quarter in java?

Something like this:

int unroundedMinutes = calendar.get(Calendar.MINUTE);
int mod = unroundedMinutes % 10;
calendar.add(Calendar.MINUTE, mod == 0 ? 10 : 10 - mod);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • In terms of speed, how the Calendar allocation and `add()` method perform compared to the `getTime()` and `/`? (needs to be fast) – Déjà vu Jan 05 '11 at 17:59
0

Your approach with the epoch time in ms will not work for arbitrary time zones, since some time zones have a N*15 minutes offset from GMT. Within these time zones, your code would move the interval 5-14 to 15, 15-24 to 25 and so on.

Have you actually tested the performance when manipulating the appropriate fields in the GregorianCalendar class and concluded that the performance is insufficient, or are you trying to reinvent a wheel just for the fun of it?

jarnbjo
  • 33,923
  • 7
  • 70
  • 94
  • I expect you to give me an advice based on my requirements. – Déjà vu Jan 05 '11 at 18:02
  • 1
    Well, your approach is obviously not reliable. It's not possible to know if the calendar approach fulfills your other requirement (fast), unless you either specify the exact meaning of "fast", provide me access to your production hardware for a benchmark and pay me for that work. Alternatively, you may of course spend five minutes yourself to check if it's fast enough? – jarnbjo Jan 05 '11 at 18:06