0

I have an array with times

String[] times = {"08:00", "09:15", "09:45", "08:15", "08:45", "09:30"};

And I want to loop through every value of the array and check if it is higher than the previous value. If that is true, it splits the array at that point so you get these two arrays:

String[] times1 = {"08:00", "09:15", "09:45"};
String[] times2 = {"08:15", "08:45", "09:30"};

How to do this in java?

2 Answers2

0

To split the array, simply use Arrays.copyOfRange to copy the left part and the right part in two new arrays.

//You first determine the split index
int splitIndex  = 2;
String[] times  = {"08:00", "09:15", "09:45", "08:15", "08:45", "09:30"};
String[] times1 = Arrays.copyOfRange(times,0,splitIndex + 1);
String[] times2 = Arrays.copyOfRange(times,splitIndex + 1,times.length);

To compare the time values, you can parse those simple strings by yourself.

public static int compareDates(String d1, String d2) {
        String[] split1 = d1.split(":");
        String[] split2 = d2.split(":");

        int n1 = Integer.parseInt(split1[0]);
        int n2 = Integer.parseInt(split2[0]);

        if (n1 != n2)
            return Integer.compare(n1,n2);
        return Integer.compare(Integer.parseInt(split1[1]),Integer.parseInt(split2[1]));
    }

The rest is up to you, you just need to iterate over the main array and use those two pieces of code in your loop.

Dici
  • 25,226
  • 7
  • 41
  • 82
0

Use following code:

String[] times = {"08:00", "09:15", "09:45", "08:15", "08:45", "09:30"};
    String first[]=null;
    String second[]=null;
    for(int i=0;i<times.length-1;i++)
    {
        Date date=new SimpleDateFormat("hh:mm").parse(times[i]);
        Date date2=new SimpleDateFormat("hh:mm").parse(times[i+1]);
        if(date.getTime()>date2.getTime())
        {
            first=Arrays.copyOfRange(times, 0, i+1);
            second=Arrays.copyOfRange(times, (i+1), (times.length));
        }
    }

Hope it helps.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34