Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a list of dates and a current date. How can I find the date which is nearest to the current date?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
751 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'd use Collection.min with a custom comparator that "orders" the dates according to distance from current time.

final long now = System.currentTimeMillis();

// Create a sample list of dates
List<Date> dates = new ArrayList<Date>();
Random r = new Random();
for (int i = 0; i < 10; i++)
    dates.add(new Date(now + r.nextInt(10000)-5000));

// Get date closest to "now"
Date closest = Collections.min(dates, 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 Long.compare(diff1, diff2);
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...