4

java.util.Date2 つのオブジェクトの日付部分を比較したい。どうすればこれを達成できますか?日付、月、年を別々に比較するつもりはありません。

前もって感謝します!

4

5 に答える 5

4

commons-lang DateUtils は、この問題に対する優れた解決策を提供します。

これを見て

これにより、2 つのインスタンスを 1 行で比較することができ、必要Dateなすべての部分が見えなくDateなります。

Date date1 = new Date(2011, 8, 30, 13, 42, 15);
    Date date2 = new Date(2011, 8, 30, 15, 23, 46);
    int compareTo = DateUtils.truncatedCompareTo(date1, date2,
            Calendar.DAY_OF_MONTH);

この例では、の値compareToは 0 です。

于 2011-09-30T11:40:40.323 に答える
3

A Date is just an instant in time. It only really "means" anything in terms of a date when you apply a calendar and time zone to it. As such, you should really be looking at Calendar, if you want to stick within the standard Java API - you can create a Calendar object with the right Date and time zone, then set the time components to 0.

However, it would be nicer to use Joda Time to start with, and its LocalDate type, which more accurately reflects what you're interested in.

于 2011-09-30T11:22:03.753 に答える
2

Use Calendar.set() with Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND to set all those fields to 0.

The answers to this duplicate question will be useful: Resetting the time part of a timestamp in Java

于 2011-09-30T11:21:55.743 に答える
1
于 2016-08-21T21:16:49.287 に答える