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

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

java - Find nearest date among several dates to a given date

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

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

1 Answer

0 votes
by (71.8m points)

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);
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...