How to check if 2 dates are on the same day in Java

后端 未结 5 1095
南方客
南方客 2021-01-13 03:56

I have 2 Date variables, Date1 and Date2. I want to check if Date 1 fall on the same date as Date2 (but they are allowed to have different times).

How do i do this?

5条回答
  •  佛祖请我去吃肉
    2021-01-13 04:50

    Today = Span Of Time

    While the other answers may be correct, I prefer the approach where we recognize that "today" is actually a span of time.

    Because of anomalies such as Daylight Saving Time (DST), days vary in length, not always 24 hours long. Here in the United States, some days are 23 hours long, some 25.

    Half-Open

    Commonly in data-time work, we use the "Half-Open" strategy where the beginning of a span is inclusive and the ending is exclusive. So that means "today" spans from the first moment of today up to, but not including, the first moment of tomorrow.

    Time Zones

    Time zones are critical, as explained in the correct answer by Meno Hochschild. The first moment of a day depends on its time zone rules.

    Joda-Time

    The Joda-Time library has nice classes for handling spans of time: Period, Duration, and Interval.

    DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
    DateTime now = new DateTime( timeZone );
    Interval today = new Interval( now.withTimeAtStartOfDay(), now.plusDays(1).withTimeAtStartOfDay() );
    
    DateTime dateTimeInQuestion = new DateTime( date ); // Convert java.util.Date.
    boolean happensToday = today.contains( dateTimeInQuestion );
    

    Benefits

    This approach using a span of time has multiple benefits:

    • Avoids Daylight Saving Time (DST) issues
    • Lets you compare date-time values from other time zones
    • Flexible, so you can use the same kind of code for other spans (multiple days, months, etc.)
    • Gets your mind shifted away from calendar dates (a layered abstraction) and onto date-times as points on a flowing timeline (the underlying truth).

    Java 8 has a new java.time package built-in. These new classes are modeled after Joda-Time but are entirely re-architected. This same kind of code can be written using java.time.

提交回复
热议问题