java.util.Date
2 つのオブジェクトの日付部分を比較したい。どうすればこれを達成できますか?日付、月、年を別々に比較するつもりはありません。
前もって感謝します!
java.util.Date
2 つのオブジェクトの日付部分を比較したい。どうすればこれを達成できますか?日付、月、年を別々に比較するつもりはありません。
前もって感謝します!
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 です。
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.
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