How to store 24 Hour format in list in Android Kotlin

Viewed 370

Hey I want to return a list of time object of 24 hours of time frame. It means i need a logic to get hours in a list starting from 00.00 to 23.00. Inside the list [00.00,01.00,02.00,.....23.00] . If i search a particular index like

println(timeList[3])

it will return

03.00.

How to i achieve this logic throught Calendar object or any other class. Does any one have idea about this how to get this type of list.

2 Answers

Use can create a List of java.time.LocalTime.

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<LocalTime> list = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            list.add(LocalTime.of(i, 0));
        }

        System.out.println(list.get(3));
    }
}

Output:

03:00

Learn more about java.time, the modern date-time API* from Trail: Date Time.

Using legacy API:

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        List<String> list = new ArrayList<>();
        
        for (int i = 0; i < 24; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, i);
            calendar.set(Calendar.MINUTE, 0);
            list.add(sdf.format(calendar.getTime()));
        }

        System.out.println(list.get(3));

    }
}

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

The kotlin version

fun main(){
    var l = mutableListOf<LocalTime>()
    (0..24).forEach {
        l.add(LocalTime.of(it,0))
    }
}
Related