开发者

Java convert time format to integer or long

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 ultim开发者_运维问答ate 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?


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];


Use java.text.SimpleDateFormat. You construct it with the desired format and then call parse(), passing the string. Then you can obtain each of the desired fields.


Depends on what exactly is your goal.

If it's simply to be able to put the times in order, then you don't need to convert them. Assuming they are really all in that 8 character format, String.compareTo() will work.

If you really want to convert them to integers first (presumably for performance reasons), just use Integer.parseInt(s.substring(0,2) + s.substring(3, 5) + s.substring(6)).


Adding to @Bozho's answer: Once you have your Date object from SimpleDateFormat you call Date.getTime() to get the time as the long you are looking for.


Parse that string using simpleDateFormat and get a Calendar instance of that then, use getTime() method of calendar instance, You will get in long format and can sort those dates.


Well, as with other suggestions here, you can use Collections.sort(ArrayList) where the Arraylist contains all date objects. If you need only the latest, pick the last value from this ArrayList. I feel this should do for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜