Sort a TreeMap if the key is date

Viewed 44

What comparator should I use to sort a TreeMap<Date, Long> if I want its keys to be "the same" if they hold the same DAY. What I'm trying to say is that I want "15.09.2022 at 12:00" and "15.09.2022 at 12:01" to be the same.

I came up with an idea

Map<Date, Long> map = new TreeMap<>((date1, date2) -> {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
    return fmt.format(date1).compareTo(fmt.format(date2));
});

But it isn't quite the best practice to cast Dates to Strings every time. Is there a more elegant way to do it?

2 Answers

Convert it to java.time, then trim off the local time.

new TreeMap<>(Comparator.comparing(
  date -> date.toInstant()
    .atZone(APPROPRIATE_TIMEZONE)
    .toLocalDate()))

(Or, better, use java.time in the first place.)

Replace APPROPRIATE_TIMEZONE with a ZoneId object for a time zone.

Note that you absolutely need a time zone; two java.util.Dates can represent different days depending on which timezone you interpret them in. (Confused? Yes, it's confusing. This is why java.util.Date got replaced with something clearer.)

Call .getTime() and integer divide it by 1000*60*60*24 (1000 milliseconds, 60 seconds, 60 minutes, 24 hours):

Date date = new Date();
Long dateDayKey = date.getTime() / 86_400_000L;

This will "chop off" the part of less resolution than a day. (getTime() gives you the number of milliseconds since 1970-01-01 00:00:00)

Related