2016-04-28 39 views
1

我有一個人的出生日期,我需要檢查他們是否在符合條件的日期之前出生(他們需要在我的情況下至少21歲) 。我想使用java.util.Date,而不是Calendar。我怎麼去檢查這個?檢查是否有特定年齡的人來自DOB - JAVA

我有這樣的事情,但它不可能有效地工作:

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

.NET,但沒有攔截http://stackoverflow.com/a/11942/706695 – HRgiger

+0

使用「日曆」的問題是什麼? – Blip

+0

是否可以使用Java8功能?例如'ChronoUnits'就像這樣:'ChronoUnit.YEARS.between(生日,今天);' –

回答

0

我會建議使用JodaTime

但是如果你想用日期來做到這一點:

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); 
} 
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. 

所以你examle可能是:

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