如何检查年龄是否在今天的18至75岁之间

huangapple go评论78阅读模式
英文:

How to check the age is between 18 and 75 years from today

问题

我已经编写了以下代码,但在以下情况下它不起作用。

LocalDate today = LocalDate.now(ZoneId.systemDefault());
DateTimeFormatter dobFormat = DateTimeFormatter.ofPattern("dd-MM-uuuu");
int age = Period.between(inputdate, today).getYears();
if (age >= 18 && age <= 75) {
    return true;
} else {
    return false;
}

它没有检查包括天数的年龄,即如果我们输入日期为24-06-1948,年龄为75岁+2天(大于75岁),但它返回true。

英文:

I have written the code like below, but it it is not working in below case.

LocalDate today = LocalDate.now(ZoneId.systemDefault());
DateTimrFormatter dobFormat = DateTimeFormatter.ofPattern(&quot;dd-MM-uuuu&quot;);
int age = Period.between(inputdate, today).getYears();
if (age &gt;= 18 &amp;&amp; age &lt;= 75) {
    return true;
} else {
    return false
}

It is not checking age including days i.e. if we give input date as 24-06-1948, then age is 75 years + 2 days (greater than 75), but it returns true.

答案1

得分: 1

你可以创建新的 Period 对象,并利用 isZeroisNegative 方法来确定比较。

Period minus18 = period.minusYears(18);
boolean gte18 = minus18.isZero() || !minus18.isNegative();
Period minus75 = period.minusYears(75);
boolean lte75 = minus75.isZero() || minus75.isNegative();
if (gte18 &amp;&amp; lte75) {

} else {

}

这是一个示例。

LocalDate today = LocalDate.now(ZoneId.systemDefault());
LocalDate[] dates = {
    LocalDate.of(1948, 6, 25), LocalDate.of(1948, 6, 26), LocalDate.of(1948, 6, 27),
    LocalDate.of(2005, 6, 25), LocalDate.of(2005, 6, 26), LocalDate.of(2005, 6, 27) };
Period period, minus18, minus75;
boolean gte18, lte75;
for (LocalDate inputdate : dates) {
    period = Period.between(inputdate, today);
    minus18 = period.minusYears(18);
    gte18 = minus18.isZero() || !minus18.isNegative();
    System.out.printf(&quot;%-12s - 18 = %-12s &gt;= 18 = %b%n&quot;, period, minus18, gte18);
    minus75 = period.minusYears(75);
    lte75 = minus75.isZero() || minus75.isNegative();
    System.out.printf(&quot;%-12s - 75 = %-12s &lt;= 75 = %b%n&quot;, period, minus75, lte75);
}

输出

P75Y1D       - 18 = P57Y1D       &gt;= 18 = true
P75Y1D       - 75 = P1D          &lt;= 75 = false
P75Y         - 18 = P57Y         &gt;= 18 = true
P75Y         - 75 = P0D          &lt;= 75 = true
P74Y11M30D   - 18 = P56Y11M30D   &gt;= 18 = true
P74Y11M30D   - 75 = P-1Y11M30D   &lt;= 75 = true
P18Y1D       - 18 = P1D          &gt;= 18 = true
P18Y1D       - 75 = P-57Y1D      &lt;= 75 = true
P18Y         - 18 = P0D          &gt;= 18 = true
P18Y         - 75 = P-57Y        &lt;= 75 = true
P17Y11M30D   - 18 = P-1Y11M30D   &gt;= 18 = false
P17Y11M30D   - 75 = P-58Y11M30D  &lt;= 75 = true
英文:

You can create new Period objects, and utilize the isZero and isNegative methods, to determine comparison.

Period minus18 = period.minusYears(18);
boolean gte18 = minus18.isZero() || !minus18.isNegative();
Period minus75 = period.minusYears(75);
boolean lte75 = minus75.isZero() || minus75.isNegative();
if (gte18 &amp;&amp; lte75) {

} else {

}

Here is an example.

LocalDate today = LocalDate.now(ZoneId.systemDefault());
LocalDate[] dates = {
    LocalDate.of(1948, 6, 25), LocalDate.of(1948, 6, 26), LocalDate.of(1948, 6, 27),
    LocalDate.of(2005, 6, 25), LocalDate.of(2005, 6, 26), LocalDate.of(2005, 6, 27) };
Period period, minus18, minus75;
boolean gte18, lte75;
for (LocalDate inputdate : dates) {
    period = Period.between(inputdate, today);
    minus18 = period.minusYears(18);
    gte18 = minus18.isZero() || !minus18.isNegative();
    System.out.printf(&quot;%-12s - 18 = %-12s &gt;= 18 = %b%n&quot;, period, minus18, gte18);
    minus75 = period.minusYears(75);
    lte75 = minus75.isZero() || minus75.isNegative();
    System.out.printf(&quot;%-12s - 75 = %-12s &lt;= 75 = %b%n&quot;, period, minus75, lte75);
}

Output

P75Y1D       - 18 = P57Y1D       &gt;= 18 = true
P75Y1D       - 75 = P1D          &lt;= 75 = false
P75Y         - 18 = P57Y         &gt;= 18 = true
P75Y         - 75 = P0D          &lt;= 75 = true
P74Y11M30D   - 18 = P56Y11M30D   &gt;= 18 = true
P74Y11M30D   - 75 = P-1Y11M30D   &lt;= 75 = true
P18Y1D       - 18 = P1D          &gt;= 18 = true
P18Y1D       - 75 = P-57Y1D      &lt;= 75 = true
P18Y         - 18 = P0D          &gt;= 18 = true
P18Y         - 75 = P-57Y        &lt;= 75 = true
P17Y11M30D   - 18 = P-1Y11M30D   &gt;= 18 = false
P17Y11M30D   - 75 = P-58Y11M30D  &lt;= 75 = true

答案2

得分: 0

我建议使用LocalDate,您可以创建两个本地日期对象,一个设置为最小日期,另一个设置为最大日期。

LocalDate minDate = LocalDate.now().minusYears(18).minusDays(1);
LocalDate maxDate = LocalDate.now().plusYears(57).plusDays(1);

以今天的日期为中心点考虑,您可以通过减去18年和1天来创建minDate,以同样的方式为75年来创建maxDate

现在您可以使用isBeforeisAfter方法来检查中间条件:

if (minDate.isBefore(toDayDate) && maxDate.isAfter(toDayDate))

注意:如果您正在寻找出生日期(DOB)的检查,请始终以DOB作为中心点。

英文:

I will recommend to use LocalDate, you can create two local date objects one with minimum date and another with maximum date

 LocalDate minDate = LocalDate.now().minusYears(18).minusDays(1);
 LocalDate maxDate = LocalDate.now().plusYears(57).plusDays(1);

Considering today's date as center point, you can create minDate with subtracting 18 years and 1 day, and the same way for maxDate of 75 years

Now you can use isBefore and isAfter methods to check in between condition

if(minDate.isBefore(toDayDate) &amp;&amp; maxDate.isAfter(toDayDate))

Note : If you are looking for DOB check, always take DOB as center point

答案3

得分: 0

以前的Joda-time库提供了解决方案。请参阅https://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java。

使用新的Java-Time API,我们有两个选项:

  • DurationcompareTo,不适用于月份和年份
  • Period与算术,请参见Reilas的答案
  • 比较不同的LocalDate

Duration用于短期和精确(周、天、毫秒/纳秒)

通常,当我们需要比较对象以表示时间间隔时,可以使用Duration,例如年龄。Duration类实现了Comparable接口,并具有一个compareTo(otherDuration)方法。

这对于近似的相对事件非常有效,例如:

  • 5分钟前更新
  • 下一次运行在2周零4天

因此,理论上我们可以将实际年龄与18岁等边界进行比较,例如actualAge.compareTo(AGE_18_YEARS)并评估返回的-101
实际上,AGE_18_YEARS的年龄参考必须被指定为Duration,它只允许ChronoUnit.Days作为最大单位。18年有多少天呢?

基于日历的Period,适用于较长时间(特别是月份和年份)

不幸的是,像一个人的年龄这样的遥远事件需要几个月甚至几年。两个chrono-units依赖于日历和它们的相对位置。月份可以是28、29、30或31天。年份可以是365天,甚至闰年的话是366天。

LocalDate在生日日历中的定位

年龄对于任何人来说都是特殊的,它有一个特殊的日期,包括一定数量的天数(取决于生日和闰年)。

让我们使用生日来评估某人是否18岁、介于之间还是75岁。

使用一个像日历、生日和日期比较这样的单一概念会导致有意义且可读的解决方案。

在IDEone上测试演示

// DOB: 2000-12-24
var dob =  LocalDate.of(2000, 12, 24);


// 最小年龄:18岁
var birthdayAge18years = dob.plusYears(18);
// 最大年龄:75岁
var birthdayAge75years = dob.plusYears(75);

var today = LocalDate.now();

// 今天是否
//      在或之后 18 岁生日
//  并在或之前 75 岁生日
var olderThanOr18 = today.equals(birthdayAge18years) || today.isAfter(birthdayAge18years);
var youngerThanOr75 = today.equals(birthdayAge75years) || today.isBefore(birthdayAge75years);

// 测试
System.out.println(birthdayAge18years + " > older than or exactly 18 years: " + olderThanOr18);
System.out.println(birthdayAge75years + " > younger than or exactly 75 years: " + youngerThanOr75);
英文:

Former library Joda-time had the solution. See https://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java.

With the new Java-Time API we have two options:

  • Duration with compareTo, not suitable for months and years
  • Period with arithmetic, see Reilas 's answer
  • compare different LocalDates

Duration for short and precise (weeks, days, milli-/nano-seconds)

Usually we can use Duration when we need to compare objects to express temporal distance like age. The Duration class implements the Comparable interface and has a method compareTo(otherDuration).

This would work for approximate relative events like:

  • updated 5 minutes ago
  • next run in 2 weeks and 4 days

So, in theory we could compare the actual-age to a boundary like 18 years like actualAge.compareTo(AGE_18_YEARS) and evaluate the returned -1, 0 or 1.
In practice the age-reference of AGE_18_YEARS must be specified as Duration which only allows ChronoUnit.Days as largest unit. How many days would be 18 years ?

Period based on calendar for long (especially months and years)

Unfortunately distant events like the age of a person take months and years. Both chrono-units depend on a calendar and their relative position. Months can be 28, 29, 30 or 31 days. Years can be 365, even 366 days for a leap-year.

LocalDate orientation within a calendar of birthdays

The age is special for any person, it has a special day and comprises a special number of days (depending on the birthday and leap-years).

Let's use the birthday to evaluate if someone is 18, in between or 75 years old.

Using a single concept like calendar, birthdays and date-comparison leads to a meaningful and readable solution.

Test the demo on IDEone:

// DOB: 2000-12-24
var dob =  LocalDate.of(2000, 12, 24);


// Minimum age: 18 years
var birthdayAge18years = dob.plusYears(18);
// Maximum age: 75 years
var birthdayAge75years = dob.plusYears(75);

var today = LocalDate.now();

// is today
//      on or after  18th birthday 
//  and on or before 75th birthday
var olderThanOr18 = today.equals(birthdayAge18years) || today.isAfter(birthdayAge18years);
var youngerThanOr75 = today.equals(birthdayAge75years) || today.isBefore(birthdayAge75years);

// test
System.out.println(birthdayAge18years + &quot; &gt; older than or exactly 18 years: &quot; + olderThanOr18);
System.out.println(birthdayAge75years + &quot; &gt; younger than or exactly 75 years: &quot; + youngerThanOr75);

答案4

得分: -1

The issue is that getYears() returns the rounded number of full years, which is 75 in this case. So what you should really do is if (age >= 18 && age < 75).

That said, I have a few more remarks:

  1. Your question should not have syntax errors.
  2. You should really, really, learn to use a debugger if you want to pursue any form of professional software development career. It is a fundamental and essential skill.
  3. For future questions, please have a look at the StackOverflow code of conduct.
英文:

The issue is that getYears() returns the rounded number of full years, which is 75 in this case. So what you should really do is if (age &gt;= 18 &amp;&amp; age &lt; 75).

That said, I have a few more remarks:

  1. Your question should not have syntax errors.
  2. You should really, really, learn to use a debugger if you want to pursue any form of professional software development career. It is a fundamental and essential skill.
  3. For future questions, please have a look at the StackOverflow code of conduct

huangapple
  • 本文由 发表于 2023年6月26日 22:41:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定