Reputation: 32680
I have a range of times with a start and an end, both of which are java.sql.Time
objects`. I want to populate a JComboBox with a list of times between them, in intervals of 15 minutes. For instance, if the start is 11:00 and the end is 12:00, I want the options in the JComboBox to be 11:00, 11:15, 11:30, 11:45 and 12:00.
Whats the most efficient way to do this?
Upvotes: 2
Views: 2730
Reputation: 347194
java.sql.Time
extends from java.util.Date
, therefore you can use it within other classes that accept Date
.
Here, I've used a Calendar
to simply modify the miniute field by 15 minute intervals until I reach the desired end time...
List<java.sql.Time> intervals = new ArrayList<>(25);
// These constructors are deprecated and are used only for example
java.sql.Time startTime = new java.sql.Time(11, 0, 0);
java.sql.Time endTime = new java.sql.Time(12, 0, 0);
intervals.add(startTime);
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
while (cal.getTime().before(endTime)) {
cal.add(Calendar.MINUTE, 15);
intervals.add(new java.sql.Time(cal.getTimeInMillis()));
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
for (java.sql.Time time : intervals) {
System.out.println(sdf.format(time));
}
This will output
11:00
11:15
11:30
11:45
12:00
Upvotes: 4
Reputation: 40036
Twisted a bit on your question: make a List containing all integers in 5-interval, between 2 integer:
First, we can know how many number there will be, and allocate the list accordingly: (all in psuedo code)
// assume begin and end is at the boundary of interval.
int noOfElement = (begin - end)/5 + 1;
List<Integer> resultList = new ArrayList<>(noOfElement);
Then populate the values in the list:
for (int i = begin; i <= end ; i += 5) {
resultList.add(i);
}
resultList will then contains all the values you want.
If you can understand this example, there is nothing special making similar logic which handles Date
Some more hints to you: look into Date#toTime()
, and Date(long Date)
Upvotes: 0