简体   繁体   中英

Sorting and comparing Java Date objects produces unexpected results

I have a number of java Date objects which I am attempting to sort in ascending date order.

These are loaded from a CSV using a simple date formatter in UK format "dd/mm/yy HH:ss", and output in the same format, eg

new SimpleDateFormat("dd/mm/yy HH:ss", Locale.ENGLISH);

This works correctly.

However, when I attempt to sort these (by implementing the Comparator interface) these are sorted incorrectly seemingly in US date format (mm/dd/yy).

    public int compare(CSVEntry t, CSVEntry t1) {
        if (t.date.before(t1.date))
            return -1;
        else if (t.date.after(t1.date))
            return 1;
        else
            return 0;
    }

This is regardless of what method I use (Date.after() or Date.before() or Date.compareTo) and regardless of what the locale is set to.

I've attempted to set the system default local using:

Locale.setDefault(Locale.ENGLISH);

To no effect.

Any ideas?

"dd/mm/yy HH:ss"

mm is minutes of the hour. You are probably looking for MM (month of the year).

Also, HH:ss ? Not HH:mm or HH:mm:ss ?

If t.date is actually a Date object then the format of your input is irrelevant. It will compare the fields of the Date object itself.

Hence it's almost certainly a problem with how you converted your text date to a Date object.

I think you need to debug that process and find out why (or if) the date is being converted incorrectly.

For a start, the format you should be using is:

dd/MM/yy HH:ss

The lower case m (as shown here ) is for minutes rather than months. I'm assuming your rather "strange" HH:ss is what you want even though it doesn't have the minutes specifier.

You may want to check that as well.

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