2

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?

drew moore
  • 31,565
  • 17
  • 75
  • 112
  • I dont know if it is the most efficient way, but I would do an Array of JComboBox, where in each element I would have a "time". What do you think? – DanielTheRocketMan Mar 15 '13 at 03:31
  • 2018 comment: today you’d prefer to use the modern `LocalTime` class rather than the long outdated and poorly designed `java.sql.Time`. – Ole V.V. Jul 11 '18 at 18:40

2 Answers2

4

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
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

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)

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
  • 1
    Also look at joda time's periods and durations. It makes it trivial to add, say, 15 minutes to a time stamp. – Michael Deardeuff Mar 15 '13 at 03:25
  • @MichaelDeardeuff I'd rather have a long, and add (15 * 60 * 1000) to get the next time. It looks as trivial and as readable in such case :) – Adrian Shum Mar 15 '13 at 03:45