java - compare two date values for the month and year
Asked Answered
D

3

5

I have a requirement to match two dates and if their month/year are same, i should return true, otherwise false. Based on my search, i found the following solution. Is there any other better way to do this comparison?.

Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(date1);
    cal2.setTime(date2);
    boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                      cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
Doriedorin answered 12/3, 2016 at 3:14 Comment(1)
This Question should be re-opened, as it is not "unclear". The Question asks how to tell if a pair of dates share the same year and month. Pretty simple question, and a reasonable one. For example, do two credit cards share the same expiration year-month.Collusive
C
12

tl;dr

match two dates and if their month/year are same

Is there any other better way to do this comparison?

Yes, the better way uses the modern java.time classes.

YearMonth.from(                                   // Represent the year-month without a day-of-month, without a time-of-day, and without a time zone.
    LocalDate.of( 2018 , Month.JANUARY , 23 ) ,   // Represent a date-only, without a time-of-day and without a time zone.
)                                                 // Returns a `YearMonth` object.
.equals(                                          // Compare one `YearMonth` object to another.
    YearMonth.now()                               // Capture today’s year-month as seen in the JVM’s current default time zone.
)

Details

Yes, there is a better way.

You are using old date-time classes bundled with the earliest versions of Java. These classes have proven to be poorly designed, confusing, and troublesome. Avoid them, including java.util.Date.

java.time

Those old classes have been supplanted by the java.time framework built into Java 8 and later.

Instant

Convert the given java.util.Date objects to Instant objects, a moment on the timeline in UTC.

Instant i1 = myJavaUtilDate1.toInstant();
Instant i2 = myJavaUtilDate2.toInstant();

We are aiming to get to YearMonth objects as you only care about the year and the month. But to get there we need to apply a time zone. The year and the month only have meaning in the context of a specific time zone, and unless you are from Iceland I doubt you want the year/month context of UTC.

ZoneId

So we need to specify the desired/expected time zone (ZoneId).

ZoneId zoneId = ZoneId.of( "America/Montreal" );

ZonedDateTime

Apply that time zone to each Instant, producing ZonedDateTime objects.

ZonedDateTime zdt1 = ZonedDateTime.ofInstant( i1 , zoneId );
ZonedDateTime zdt2 = ZonedDateTime.ofInstant( i2 , zoneId );

YearMonth

Now extract YearMonth objects.

YearMonth ym1 = YearMonth.from( zdt1 );
YearMonth ym2 = YearMonth.from( zdt2 );

Compare.

Boolean same = ym1.equals( ym2 );

By the way, you likely have other business logic involving the year and month. Remember that the java.time classes are built into Java now. So you can use and pass YearMonth objects throughout your code base rather than re-calculating or passing strings.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Collusive answered 12/3, 2016 at 4:55 Comment(0)
M
1

Fast way: With JodaTime libary.

  • First, make sure that you downloaded/implemented it.
  • Then import.
import org.joda.time.LocalDate;
import java.util.Date;
  • Here you go:
Date Date1 = new Date();
Date Date2 = new Date();

if (new LocalDate(Date1).getYear() == new LocalDate(Date2).getYear()) {
 // Year Matches
 if (new LocalDate(Date1).getMonthOfYear() == new LocalDate(Date2).getMonthOfYear()) {
  // Year and Month Matches
 }
}
Monosymmetric answered 3/7, 2020 at 8:39 Comment(0)
D
0

You can use date1.getYear() == date2.getYear() && date1.getMonth() == date2.getMonth()

Dehypnotize answered 12/3, 2016 at 3:15 Comment(2)
getYear() etc are DeprecatedAlsoran
getYear() and getMonth() are not only deprecated, they have been deprecated sine February 1997 because they work unreliably across time zones. And the whole Date class is poorly designed and long outdated. If you cannot avoid getting one, convert to ZonedDateTime as shown in the answer by Basil Bourque.Smelly

© 2022 - 2024 — McMap. All rights reserved.