Roman Roman - 1 month ago 14
Java Question

How to trim minutes and hours and seconds from Date object?

I need to make map where Dates are keys. 2 date objects are equals if they have the same value of

getTime()
method.

I'm interested only in year, month and day. How can I
trim
unnecessary hours and minutes to get 'clear' dates?

Answer

Use a custom Comparator<Date> for a TreeMap<Date,V>.

    Comparator<Date> ymdComparator = new Comparator<Date>() {
        @Override public int compare(Date d1, Date d2) {
            return 
                d1.getYear() < d2.getYear() ? -1 :
                d1.getYear() > d2.getYear() ? +1 :
                d1.getMonth() < d2.getMonth() ? -1 :
                d1.getMonth() > d2.getMonth() ? +1 :
                d1.getDay() < d2.getDay() ? -1 :
                d1.getDay() > d2.getDay() ? +1 :
                0;
        }
    };

    SortedMap<Date,V> map = new TreeMap<Date,V>(ymdComparator);

Oh, java.util.Date sucks, use Joda Time, etc.

Comments