Reputation: 39
Have a start time and end time that has to be split into equal interval.
E.g.
Start Time: 10AM, End Time: 14PM, Split Time: 30 minutes
The output has to be something like this -
::::Output :::
[{time:"10:00"},{time:"10:30"},{time:"11:00"},{time:"11:30"},{time:"12:00"},{time:"12:30"},{time:"13:00"},{time:"13:30"},{time:"14:00"}]
Thanks everyone in advance.
Upvotes: 0
Views: 5455
Reputation: 31225
First, convert hours to minutes.
10AM = 10 * 60 minutes
2PM or 14h = 14 * 60 minutes
Then, in order to convert minutes back to hours :
minutes / 60 gives the number of hours
minutes % 60 gives the number of the minutes in the last hour.
If you want to display hours/minutes always on 2 digits, and eventually pad with a leading zero, use :
String result = String.format("%02d", minutes/60);
(2
indicates that you want 2 digits and 0
indicates that you pad with zeros)
That said, there are 2 ways of going from 10*60
to 14*60
with steps of 30 minutes
:
The most intuitive : the while loop
public static void interval(int begin, int end, int interval) {
int time = begin;
while (time <= end) {
System.out.println(String.format("%02d:%02d", time / 60, time % 60));
time += interval;
}
}
But I don't like while
loops. If you do it wrong (or if the input data are wrong), it ends in infinite loops.
The other way : as you know the begin, the end and the step, use a for
loop :
public static void interval2(int begin, int end, int interval) {
for (int time = begin; time <= end; time += interval) {
System.out.println(String.format("%02d:%02d", time / 60, time % 60));
}
}
Test :
interval2(10 * 60, 14 * 60, 30);
Result :
10:00
10:30
11:00
11:30
12:00
12:30
13:00
13:30
14:00
Upvotes: 4