Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert time format to integer or long

Tags:

java

string

time

I'm wondering what the best method is to convert a time string in the format of 00:00:00 to an integer or a long? My ultimate goal is to be able to convert a bunch of string times to integers/longs, add them to an array, and find the most recent time in the array...

I'd appreciate any help, thanks!


Ok, based on the answers, I have decided to go ahead and compare the strings directly. However, I am having some trouble. It is possible to have more than one "most recent" time, that is, if two times are equal. If that is the case, I want to add the index of both of those times to an ArrayList. Here is my current code:

    days[0] = "15:00:00";
    days[1] = "17:00:00";
    days[2] = "18:00:00";
    days[3] = "19:00:00";
    days[4] = "19:00:00";
    days[5] = "15:00:00";
    days[6] = "13:00:00";

    ArrayList<Integer> indexes = new ArrayList<Integer>();
    String curMax = days[0];

    for (int x = 1; x < days.length1; x++) {
        if (days[x].compareTo(curMax) > 0) {
            curMax = days[x];
            indexes.add(x);
            System.out.println("INDEX OF THE LARGEST VALUE: " + x);
        }
    }

However, this is adding index 1, 2, and 3 to the ArrayList...

Can anyone help me?

like image 225
littleK Avatar asked Jun 14 '26 14:06

littleK


1 Answers

You can find the most recent time by comparing the strings, you don't need to convert to a long first.

e.g.

 String[] times = { "12:23:45", "23:59:59", "00:00:00" }
 Arrays.sort(times);
 String firstTime = times[0];
 String lastTime = times[times.length-1];
like image 160
Peter Lawrey Avatar answered Jun 17 '26 06:06

Peter Lawrey