获取离当前时间最近的时间

Get closest time to current time

我有日期对象数组:

Date[] vakitlarDate;

我想从该区域获取到当前时间的关闭时间。

我可以根据上面的数组计算当前时间的下一个时间 vakitlerDate

我用过这个功能:

    @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) {
                // Next time is morning of next day
                // TODO: add one day here to get next day morning
                nextTime = vakitlarDate[0];
            }

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

我只是无法从该数组中获得距现在最近的时间。

该地区从早到晚都有订单。而且是同一天的时间

有什么想法吗?

我认为你应该使用 before() 而不是 after()

我解决了:

            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 最接近现在