1

I have a person's Date Of Birth and I need to check if they were born before an eligible date ( they need to be at least 21 years of age in my scenario). I would like to to use java.util.Date, not Calendar. How would I go about checking this?

I have something like this but it could never work efficiently:

Date eligableDate = new Date(28/04/1995);       
drivingLicence.getDOB().before(eligableDate)
CubeJockey
  • 2,209
  • 8
  • 24
  • 31
Jack
  • 35
  • 5

2 Answers2

0

I would recommend using JodaTime

But if you want to do it with Date:

private static final long MILLIS_IN_SECOND = 1000L;
private static final long SECONDS_IN_MINUTE = 60L;
private static final long MINUTES_IN_HOUR = 60L;
private static final long HOURS_IN_DAY = 24L;
private static final long DAYS_IN_YEAR = 365L;
private static final long MILLISECONDS_IN_YEAR = MILLIS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY * DAYS_IN_YEAR;
private static final int AGE_LIMIT = 21;

private boolean isEligible(final Date dateOfBirth) {
    long yearLimitInLong = AGE_LIMIT * MILLISECONDS_IN_YEAR;
    Date date = new Date();
    Date dateThreshold = new Date(date.getTime() - yearLimitInLong);

    return dateOfBirth.before(dateThreshold);
}
gybandi
  • 1,880
  • 1
  • 11
  • 14
0

The Date format in your example, I think, is incorrect. Please take a look at the following:

public Date(int year, int month, int date) {
    this(year, month, date, 0, 0, 0);
}

 * @param   year    the year minus 1900.
 * @param   month   the month between 0-11.
 * @param   date    the day of the month between 1-31.

So your examle could be:

import java.util.Date;
Date eligableDate = new Date(95, 4, 28);
drivingLicence.getDOB().before(eligableDate);
Quinn
  • 4,394
  • 2
  • 21
  • 19