androidarraysdateandroid-date

Get closest time to current time


I have array of Date objects:

Date[] vakitlarDate;

I want to get the closes time to the current time from that area.

I could calculate the next time of the current time from the array above which is vakitlerDate

I used this function:

    @Override
    public void run() {
        // nextTime will be calculated here, which is the next time
        nextTime = new Date();
        Date now = new Date();
        try {
            Date[] vakitlarDate = vakitler.getVakitlarAsDateArray();
            boolean morningIsNextTime = true;
            // For loop to get next time of now
            for (int i = 0; i < Vakitler.NUM_OF_VAKITLER; i++) {
                if (now.after(vakitlarDate[i])) {
                    continue;
                } else {
                    nextTime = vakitlarDate[i];
                    currentTimeIndex = i;
                    morningIsNextTime = false;
                    break;
                }
            }

            if (morningIsNextTime) {
                nextTime = vakitlarDate[0];
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        

I just couldn't get the closest time to now from that array.

The area is ordered from morning to evening. and it is times at same date.

Any ideas ?


Solution

  • I solved it:

                List<Date> vakitlerDateList = getVakitlerAsListOfDate();
                Date closest = Collections.min(vakitlerDateList, new Comparator<Date>() {
                    public int compare(Date d1, Date d2) {
                        long diff1 = Math.abs(d1.getTime() - now);
                        long diff2 = Math.abs(d2.getTime() - now);
                        return diff1 < diff2 ? -1 : 1;
                    }
                });
    

    closest will be the closest to now