简体   繁体   中英

Sort a TreeMap if the key is date

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 Date s to String s every time. Is there a more elegant way to do it?

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.)

Note that you absolutely need a timezone; two java.util.Date s 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() / 86400000L;

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM