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

后端 未结 5 1056
南方客
南方客 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:44

    Why don't you simply compare the year, month and day? You can write your method for doing it something like:

    private boolean isDateSame(Calendar c1, Calendar c2) {
        return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && 
                c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) &&
                c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH));
    }
    
    0 讨论(0)
  • 2021-01-13 04:48

    When you use the toString() method what do you get? Is it only the year/month/day or time too? If it is then you could simply compare the strings of the two objects. (date1.toString().equals(date2.toString()));

    0 讨论(0)
  • 2021-01-13 04:49

    Although given answers based on date component parts of a java.util.Date are sufficient in many parts, I would stress the point that a java.util.Date is NOT a date but a kind of UNIX-timestamp measured in milliseconds. What is the consequence of that?

    Date-only comparisons of Date-timestamps will depend on the time zone of the context. For example in UTC time zone the date-only comparison is straight-forward and will finally just compare year, month and day component, see other answers (I don't need to repeat).

    But consider for example the case of Western Samoa crossing the international dateline in 2011. You can have valid timestamps of type java.util.Date, but if you consider their date parts in Samoa you can even get an invalid date (2011-12-30 never existed in Samoa locally) so a comparison of just the date part can fail. Furthermore, depending on the time zone the date component can generally differ from local date in UTC zone by one day, ahead or behind, in worst case there are even two days difference.

    So following extension of solution is slightly more precise:

    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
    fmt.setTimeZone(...); // your time zone
    return fmt.format(date1).equals(fmt.format(date2));
    

    Similar extension also exists for the more programmatic approach to first convert the j.u.Date-timestamp into a java.util.GregorianCalendar, then setting the time zone and then compare the date components.

    0 讨论(0)
  • 2021-01-13 04:49
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
    return fmt.format(date1).equals(fmt.format(date2));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题