fareed - 6 months ago 24
Java Question

# Integer Time Intervals

This question is more of a math problem (Sorry, I'm not good in Math).

I have time represented as integer

for example

``````700 (means 7:00)

1330 (means 13:30)

2359 (means 23:59)
``````

I have a starting time and ending time and want to create 15 minutes intervals between them. For example

``````int start = 700;
int end = 1300;
``````

I want to loop over the starting time to increment 15 minutes and jump over 60 to next hundred. For example 700, 715, 730, 745, 800, 815, 830.. etc.

I can create this by creating a
`Calendar`
object and parse the integer as
`SimpleDateFormat`
, add the time to calendar, increase the minutes, and parse the hours and minutes back to integer. But its way too long to do it, there should be a simple mathematical way to perform this more efficiently.

If you must use integers, or are decided to, you can create a method "plusMinutes", like:

``````public int plusMinutes (int time, int minutes) {
int auxMinutes = time % 60;
auxMinutes += minutes;
time += 100 * (seconds / 60);
time = 100 * (time / 100); // set the last 2 digits to 0
time += auxMinutes % 60;

return time;
}
``````

Another option (better in my opinion) is to create a method "toMinutes" and a method "toEncoded", like:

``````public int toMinutes (int encoded) {
int minutes = encoded % 100;
minutes += (encoded / 100) * 60;
return minutes;
}

public int toEncoded (int minutes) {
int encoded = minutes % 60;
encoded += (minutes / 60) * 100;
return encoded;
}
``````

NOTE: Not 100% sure if the code works, haven't tested, but you should get the general idea.

EDIT: And for your problem when using the last option, you just have to do something like:

``````int encoded = 1330;
int plusMinutes = 45;

int minutes = toMinutes(encoded);
minutes += plusMinutes;

encoded = toEncoded(minutes);
``````
Source (Stackoverflow)