检查是某人与DOB有特定年龄 - JAVA

时间:2016-04-28 12:22:29

标签: java

我有一个人的出生日期,我需要检查他们是否在符合条件的日期之前出生(在我的情景中他们需要至少21岁)。我想使用java.util.Date,而不是Calendar。我该怎么做呢?

我有类似的东西,但它永远无法有效地工作:

Date eligableDate = new Date(28/04/1995);       
drivingLicence.getDOB().before(eligableDate)

2 个答案:

答案 0 :(得分:0)

我建议使用JodaTime

但是如果你想用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);
}

答案 1 :(得分:0)

我认为您的示例中的日期格式不正确。请看一下以下内容:

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.

所以你的考试可能是:

import java.util.Date;
Date eligableDate = new Date(95, 4, 28);
drivingLicence.getDOB().before(eligableDate);