简体   繁体   English

排序和比较Java Date对象会产生意外结果

[英]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. 我有一些java Date对象,我试图按升序对它们进行排序。

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 使用英国格式“ dd / mm / yy HH:ss”的简单日期格式从CSV加载这些格式,并以相同格式输出,例如

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). 但是,当我尝试对它们进行排序(通过实现Comparator接口)时,它们似乎错误地以美国日期格式(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. 这与我使用哪种方法(Date.after()或Date.before()或Date.compareTo)无关,并且与语言环境设置无关。

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. mm是小时的分钟数。 You are probably looking for MM (month of the year). 您可能正在寻找MM (一年中的月份)。

Also, HH:ss ? 另外, HH:ss吗? Not HH:mm or HH:mm:ss ? 不是HH:mmHH:mm:ss吗?

If t.date is actually a Date object then the format of your input is irrelevant. 如果t.date实际上是一个Date对象,则您输入的格式无关紧要。 It will compare the fields of the Date object itself. 它将比较Date对象本身的字段。

Hence it's almost certainly a problem with how you converted your text date to a Date object. 因此,几乎可以肯定的是,如何将文本日期转换为Date对象。

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. 下壳体m (如所示在这里 )为分钟,而不是个月。 I'm assuming your rather "strange" HH:ss is what you want even though it doesn't have the minutes specifier. 我假设您想要的是“奇怪的” HH:ss尽管它没有分钟指示符。

You may want to check that as well. 您可能还需要检查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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