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?
CodePudding user response:
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.)
CodePudding user response:
Call .getTime()
and integer divide it by 10006060*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)