用Java中的当前日期和出生日期计算年龄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21393717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:26:19  来源:igfitidea点击:

Calculating age with current date and birth date in Java

javadatetime

提问by user3242445

I'm just starting out with java, and i'm making a program that determines a person's car rental rates, based on age and gender. This method is calculating the person's age based off of the current date and their birth date. it sort of works, but there's a problem with borderline cases (for example sometimes it will say you're 25 when you're 24). How can i fix it to make it return the exact age instead of it saying you're 1 year older sometimes? (and please no Joda, i can't use it in this assignment)

我刚开始使用 java,我正在制作一个程序,根据年龄和性别确定一个人的汽车租赁费率。此方法根据当前日期和出生日期计算此人的年龄。它有点工作,但边界情况存在问题(例如,有时它会说你 24 岁时 25 岁)。我该如何修复它以使其返回确切的年龄,而不是有时说您大 1 岁?(请不要乔达,我不能在这个作业中使用它)

public static int calcAge(int curMonth, int curDay, int curYear,int birthMonth,int   birthDay,int birthYear) {

  int yearDif = curYear - birthYear;
  int age = 08;
  if(curMonth < birthMonth) {
     age = yearDif - 1;
     }
  if(curMonth == birthMonth) {
     if(curDay < birthDay) {
        age = yearDif - 1;
        }
     if(curDay > birthDay) {
        age = yearDif;
        }
     }
  if(curMonth > birthMonth) {
     age = yearDif;
     }

  return age;
  }

采纳答案by user2684301

If you can use Java 8, it's much better than joda:

如果你能用Java 8,那比joda好多了:

    LocalDate birthday = LocalDate.of(1982, 01, 29);
    long yearsDelta = birthday.until(LocalDate.now(), ChronoUnit.YEARS);
    System.out.println("yearsDelta = " + yearsDelta);

回答by Marenthyu

You can try to use "Date" to convert both times to epoch milliseconds and then simply subtract these and get the difference converted back to year values by simple math. Get it? This would be without any extra libraries :)

您可以尝试使用“日期”将两个时间都转换为纪元毫秒,然后简单地减去这些时间,然后通过简单的数学运算将差异转换回年份值。得到它?这将没有任何额外的库:)

回答by CheeseFerret

You need to check for equals when you are comparing the days e.g

当您比较天数时,您需要检查是否相等,例如

else if (curDay >= birthDay) {
    age = yearDif;
}

instead of

代替

if(curDay > birthDay) {
    age = yearDif;
}