user2257123 user2257123 - 7 days ago 4
Java Question

String list of time with 15 minutes intervals

I need an

ArrayList
of
String
of times like:

00:00:00, 00:15:00, 00:30:00, .... 07:45:00, 08:00:00 ...... 23:30:00, 23:45:00


Without using enum class but with
java.time
API.

Answer

You create the List, you create a LocalTime initialize to 00:00, add it to the list, and then add 15min to it and do it again :

ArrayList<String> timeList = new ArrayList<>();
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime time = LocalTime.MIN;

for (int i = 0; i < 96; i++) {
    timeList.add(time.format(timeFormat));
    time = time.plusMinutes(15);
}

Or a different way (to avoid to find the 96 number), you add the 00:00 and then at the end of the iteration (in the while) you increment of 15min and check if you are back again to 00:00

ArrayList<String> timeList = new ArrayList<>();
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime time = LocalTime.MIN;

do {
     timeList.add(time.format(timeFormat));
} while ((!(time = time.plusMinutes(15)).equals(LocalTime.MIN)));