0

I have a string array that stores a bus interval for each day like this

eg. ["6:30", "6:45", "7:00", "7:15", "7:30", "7.45"..................]

I want the program to find the nearest times from the array for that day and the time on the system.

eg. in above string array say my system time is 7:35 then it should display 7:30 and 7:45 as nearest times

SST
  • 2,054
  • 5
  • 35
  • 65
  • check this: http://stackoverflow.com/questions/3884644/find-nearest-date-from-a-list you can implement your own comparator. You can also transform times to minutes etc. – xro7 Jun 15 '16 at 09:03
  • It would be a lot easier if you stored [`LocalTime`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html) instances in the array. – Andy Turner Jun 15 '16 at 09:07
  • You are going to try and compare time to strings. I would suggest to convert the strings to times and go forward from there. – Wesley De Keirsmaeker Jun 15 '16 at 09:18

2 Answers2

0

I hope this would help you out.

public class TestClass {

    public static void main(String[] args){

        String arr[]={"06:30","07:00","07:30","14:20","14:50","18:20"};
         Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            System.out.println("Your system time is :"+ sdf.format(cal.getTime()) );
            System.out.println("So nearest timings are...");
            String sys[]=sdf.format(cal.getTime()).toString().split(":");
           // System.out.println(sys[0]);
        for(String st:arr){
            if(st.startsWith(sys[0]))
                System.out.println(st);
            }
        }   
}

.

output would be : 
Your system time is :14:47 
So nearest timings are... 
14:20 14:50
san544
  • 72
  • 10
  • The above code how should work for the time "06:50"? It will return only "06:30" but it should return "6:30" and "07:00" – SST Jun 16 '16 at 05:07
0

try this

    String[] arr =new String[]{"6:30", "6:45", "7:00", "7:15", "7:30", "7:45"};
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
        String currentTime=sdf.format(cal.getTime());
        //nus interval 
        Integer interval=15;

        for (String string : arr) {
            if(Math.abs(Integer.valueOf(string.replaceFirst(":", ""))-Integer.valueOf(currentTime))<interval){
                System.out.println(string);
            } 
        }
kedar kamthe
  • 8,048
  • 10
  • 34
  • 46