【问题标题】:How do I calculate someone's age in Java?如何在 Java 中计算某人的年龄?
【发布时间】:2010-11-10 02:37:15
【问题描述】:

我想在 Java 方法中以 int 形式返回年龄。 我现在拥有的是以下内容,其中 getBirthDate() 返回一个 Date 对象(带有出生日期;-)):

public int getAge() {
    long ageInMillis = new Date().getTime() - getBirthDate().getTime();

    Date age = new Date(ageInMillis);

    return age.getYear();
}

但是由于 getYear() 已被弃用,我想知道是否有更好的方法来做到这一点?我什至不确定这是否能正常工作,因为我还没有进行单元测试。

【问题讨论】:

  • 改变了我的想法:另一个问题只有日期之间的近似年份,而不是真正正确的年龄。
  • 鉴于他返回的是一个 int,你能澄清一下你所说的“正确”年龄是什么意思吗?
  • 日期与日历是一个基本概念,可以从阅读 Java 文档中收集到。我不明白为什么这会受到如此多的赞成。
  • @demongolem ???日期和日历很容易理解?!一点都不。在 Stack Overflow 上有无数关于这个主题的问题。 Joda-Time 项目产生了最受欢迎的库之一,以替代那些麻烦的日期时间类。后来,Sun、Oracle 和 JCP 社区接受了JSR 310 (java.time),承认遗留类的不足是无可救药的。有关详细信息,请参阅Tutorial by Oracle

标签: java date calendar


【解决方案1】:

JDK 8 让这一切变得简单而优雅:

public class AgeCalculator {

    public static int calculateAge(LocalDate birthDate, LocalDate currentDate) {
        if ((birthDate != null) && (currentDate != null)) {
            return Period.between(birthDate, currentDate).getYears();
        } else {
            return 0;
        }
    }
}

一个 JUnit 测试来演示它的使用:

public class AgeCalculatorTest {

    @Test
    public void testCalculateAge_Success() {
        // setup
        LocalDate birthDate = LocalDate.of(1961, 5, 17);
        // exercise
        int actual = AgeCalculator.calculateAge(birthDate, LocalDate.of(2016, 7, 12));
        // assert
        Assert.assertEquals(55, actual);
    }
}

现在每个人都应该使用 JDK 8。所有早期版本均已结束其支持生命周期。

【讨论】:

  • 在处理闰年时,DAY_OF_YEAR 比较可能会导致错误结果。
  • 变量 dateOfBirth 必须是 Date 对象。如何创建带有出生日期的 Date 对象?
  • 鉴于我们已经9年了,如果使用Java 8,这应该是要使用的解决方案。
  • JDK 9 是当前的生产版本。比以往任何时候都更真实。
  • @SteveOh 我不同意。我宁愿完全不接受nulls,而是使用Objects.requireNonNull
【解决方案2】:

查看Joda,它简化了日期/时间计算(Joda 也是新标准 Java 日期/时间 API 的基础,因此您将学习一个即将成为标准的 API)。

编辑:Java 8 有 something very similar,值得一试。

例如

LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);

这很简单。 Java 8 之前的东西(如您所见)有些不直观。

【讨论】:

  • @HoàngLong:来自 JavaDocs:“这个类不代表一天,而是午夜的毫秒瞬间。如果你需要一个代表一整天的类,那么 Interval 或 LocalDate 可能是更适合。”我们真的确实想在这里代表一个日期。
  • 如果你想按照@JohnSkeet 建议的方式做,就像这样:Years age = Years.yearsBetween(new LocalDate(getBirthDate()), new LocalDate());
  • 不知道 为什么 我使用了 DateMidnight,我注意到它现在已被弃用。现在改为使用 LocalDate
  • @IgorGanapolsky 实际上,主要区别在于:Joda-Time 使用构造函数,而 Java-8 和 ThreetenBP 使用静态工厂方法。对于 Joda-Time 计算年龄的方式中的一个细微错误,请查看my answer,其中我对不同库的行为进行了概述。
【解决方案3】:

现代答案和概述

a) Java-8 (java.time-package)

LocalDate start = LocalDate.of(1996, 2, 29);
LocalDate end = LocalDate.of(2014, 2, 28); // use for age-calculation: LocalDate.now()
long years = ChronoUnit.YEARS.between(start, end);
System.out.println(years); // 17

请注意,表达式LocalDate.now() 隐含地与系统时区相关(这通常被用户忽略)。为了清楚起见,通常最好使用重载方法now(ZoneId.of("Europe/Paris")) 指定一个明确的时区(这里以“欧洲/巴黎”为例)。如果请求系统时区,那么我个人的偏好是写LocalDate.now(ZoneId.systemDefault()) 以使与系统时区的关系更清晰。这是更多的写作努力,但使阅读更容易。

b) 乔达时间

请注意,建议和接受的 Joda-Time-solution 对上面显示的日期产生不同的计算结果(一种罕见的情况),即:

LocalDate birthdate = new LocalDate(1996, 2, 29);
LocalDate now = new LocalDate(2014, 2, 28); // test, in real world without args
Years age = Years.yearsBetween(birthdate, now);
System.out.println(age.getYears()); // 18

我认为这是一个小错误,但 Joda 团队对这种奇怪的行为有不同的看法,并且不想修复它(很奇怪,因为结束日期的月份日期小于开始日期的日期,所以年应该少一年)。另请参阅此已关闭的issue

c) java.util.Calendar 等

为了比较,请参阅其他各种答案。我根本不建议使用这些过时的类,因为在某些特殊情况下生成的代码仍然容易出错和/或考虑到原始问题听起来如此简单这一事实过于复杂。在 2015 年,我们有了更好的库。

d) 关于 Date4J:

建议的解决方案很简单,但有时会在闰年时失败。仅仅评估一年中的哪一天是不可靠的。

e) 我自己的库 Time4J

这与 Java-8-solution 类似。只需将LocalDate 替换为PlainDate 并将ChronoUnit.YEARS 替换为CalendarUnit.YEARS。但是,获取“今天”需要明确的时区参考。

PlainDate start = PlainDate.of(1996, 2, 29);
PlainDate end = PlainDate.of(2014, 2, 28);
// use for age-calculation (today): 
// => end = SystemClock.inZonalView(EUROPE.PARIS).today();
// or in system timezone: end = SystemClock.inLocalView().today();
long years = CalendarUnit.YEARS.between(start, end);
System.out.println(years); // 17

【讨论】:

  • 感谢 Java 8 版本!节省了我一些时间:) 现在我只需要弄清楚如何提取剩余的月份。例如。 1年1个月。 :)
  • @thomas77 感谢您的回复,可以使用 Java-8 中的 `java.time.Period' 组合年和月(可能还有几天)。如果您还想考虑其他单位,例如小时,那么 Java-8 不提供解决方案。
  • 再次感谢您(以及快速回复):)
  • 我建议在使用LocalDate.now指定一个时区。如果省略,则隐式应用 JVM 的当前默认时区。该默认值可以在机器/操作系统/设置之间更改,也可以在任何时候在运行时通过任何代码调用setDefault。我建议具体一点,比如LocalDate.now( ZoneId.for( "America/Montreal" ) )
  • @GoCrafter_LP 是的,您可以将 ThreetenABP 模拟 Java-8 或 Joda-Time-Android(来自 D. Lew)或我的 lib Time4A 用于此类较旧的 Android 版本。
【解决方案4】:
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(...);
if (dob.after(now)) {
  throw new IllegalArgumentException("Can't be born in the future");
}
int year1 = now.get(Calendar.YEAR);
int year2 = dob.get(Calendar.YEAR);
int age = year1 - year2;
int month1 = now.get(Calendar.MONTH);
int month2 = dob.get(Calendar.MONTH);
if (month2 > month1) {
  age--;
} else if (month1 == month2) {
  int day1 = now.get(Calendar.DAY_OF_MONTH);
  int day2 = dob.get(Calendar.DAY_OF_MONTH);
  if (day2 > day1) {
    age--;
  }
}
// age is now correct

【讨论】:

  • 是的,日历课很糟糕。不幸的是,在工作中有时我必须使用它:/。感谢 Cletus 发布此内容
  • 将 Calendar.MONTH 和 Calendar.DAY_OF_MONTH 替换为 Calendar.DAY_OF_YEAR 至少会干净一些
  • @Tobbbe 如果您出生于闰年的 3 月 1 日,那么您的生日是下一年的 3 月 1 日,而不是 2 日。 DAY_OF_YEAR 不起作用。
【解决方案5】:
/**
 * This Method is unit tested properly for very different cases , 
 * taking care of Leap Year days difference in a year, 
 * and date cases month and Year boundary cases (12/31/1980, 01/01/1980 etc)
**/

public static int getAge(Date dateOfBirth) {

    Calendar today = Calendar.getInstance();
    Calendar birthDate = Calendar.getInstance();

    int age = 0;

    birthDate.setTime(dateOfBirth);
    if (birthDate.after(today)) {
        throw new IllegalArgumentException("Can't be born in the future");
    }

    age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);

    // If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year   
    if ( (birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3) ||
            (birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH ))){
        age--;

     // If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
    }else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH )) &&
              (birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH ))){
        age--;
    }

    return age;
}

【讨论】:

  • 检查(birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3)的目的是什么?月份和月份比较的存在似乎毫无意义。
【解决方案6】:

我只是使用一年中的毫秒常量值来发挥我的优势:

Date now = new Date();
long timeBetween = now.getTime() - age.getTime();
double yearsBetween = timeBetween / 3.15576e+10;
int age = (int) Math.floor(yearsBetween);

【讨论】:

  • 这不是准确的答案...年份不是 3.156e+10 而是 3.15576e+10(季度日!)
  • 这不起作用,有些年份是闰年并且有不同的毫秒值
【解决方案7】:

如果你使用 GWT,你将被限制使用 java.util.Date,这里有一个将日期作为整数的方法,但仍然使用 java.util.Date:

public int getAge(int year, int month, int day) {
    Date now = new Date();
    int nowMonth = now.getMonth()+1;
    int nowYear = now.getYear()+1900;
    int result = nowYear - year;

    if (month > nowMonth) {
        result--;
    }
    else if (month == nowMonth) {
        int nowDay = now.getDate();

        if (day > nowDay) {
            result--;
        }
    }
    return result;
}

【讨论】:

    【解决方案8】:

    可能令人惊讶的是,您不需要知道一年中有多少天或几个月,或者这些月有多少天,同样,您不需要知道闰年、闰秒,或任何使用这种简单、100% 准确的方法的东西:

    public static int age(Date birthday, Date date) {
        DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        int d1 = Integer.parseInt(formatter.format(birthday));
        int d2 = Integer.parseInt(formatter.format(date));
        int age = (d2-d1)/10000;
        return age;
    }
    

    【讨论】:

    • 我正在寻找 java 6 和 5 的解决方案。这既简单又准确。
    • 为了 NullPointerException 安全请添加 if (birthday != null && date != null),并返回默认值 0。
    • 我宁愿它崩溃也不愿默认年龄为 0 并继续在其他地方造成错误。想象一下:如果我问你“我出生于 ___,今天是 2021 年 3 月 17 日,我多大了?”你会说“我无法回答”,而不是“你是 0”
    【解决方案9】:

    这是上述版本的改进版本...考虑到您希望 age 成为“int”。因为有时你不想用一堆库来填充你的程序。

    public int getAge(Date dateOfBirth) {
        int age = 0;
        Calendar born = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        if(dateOfBirth!= null) {
            now.setTime(new Date());
            born.setTime(dateOfBirth);  
            if(born.after(now)) {
                throw new IllegalArgumentException("Can't be born in the future");
            }
            age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);             
            if(now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR))  {
                age-=1;
            }
        }  
        return age;
    }
    

    【讨论】:

      【解决方案10】:

      使用JodaTime的正确答案是:

      public int getAge() {
          Years years = Years.yearsBetween(new LocalDate(getBirthDate()), new LocalDate());
          return years.getYears();
      }
      

      如果您愿意,您甚至可以将其缩短为一行。我从BrianAgnew's answer 复制了这个想法,但我相信这更正确,正如您从那里的 cmets 看到的那样(它准确地回答了问题)。

      【讨论】:

        【解决方案11】:

        使用date4j 库:

        int age = today.getYear() - birthdate.getYear();
        if(today.getDayOfYear() < birthdate.getDayOfYear()){
          age = age - 1; 
        }
        

        【讨论】:

          【解决方案12】:

          尝试将这个复制到你的代码中,然后使用方法获取年龄。

          public static int getAge(Date birthday)
          {
              GregorianCalendar today = new GregorianCalendar();
              GregorianCalendar bday = new GregorianCalendar();
              GregorianCalendar bdayThisYear = new GregorianCalendar();
          
              bday.setTime(birthday);
              bdayThisYear.setTime(birthday);
              bdayThisYear.set(Calendar.YEAR, today.get(Calendar.YEAR));
          
              int age = today.get(Calendar.YEAR) - bday.get(Calendar.YEAR);
          
              if(today.getTimeInMillis() < bdayThisYear.getTimeInMillis())
                  age--;
          
              return age;
          }
          

          【讨论】:

          • 不鼓励仅使用代码回答。最好解释一下为什么这段代码可以解决 OP 问题。
          • 这其实很简单......但会更新以解决您的问题
          【解决方案13】:

          我用这段代码来计算年龄,希望对你有所帮助..没有使用任何库

          private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
          
          public static int calculateAge(String date) {
          
              int age = 0;
              try {
                  Date date1 = dateFormat.parse(date);
                  Calendar now = Calendar.getInstance();
                  Calendar dob = Calendar.getInstance();
                  dob.setTime(date1);
                  if (dob.after(now)) {
                      throw new IllegalArgumentException("Can't be born in the future");
                  }
                  int year1 = now.get(Calendar.YEAR);
                  int year2 = dob.get(Calendar.YEAR);
                  age = year1 - year2;
                  int month1 = now.get(Calendar.MONTH);
                  int month2 = dob.get(Calendar.MONTH);
                  if (month2 > month1) {
                      age--;
                  } else if (month1 == month2) {
                      int day1 = now.get(Calendar.DAY_OF_MONTH);
                      int day2 = dob.get(Calendar.DAY_OF_MONTH);
                      if (day2 > day1) {
                          age--;
                      }
                  }
              } catch (ParseException e) {
                  e.printStackTrace();
              }
              return age ;
          }
          

          【讨论】:

            【解决方案14】:

            出生和效果字段都是日期字段:

            Calendar bir = Calendar.getInstance();
            bir.setTime(birth);
            int birthNm = bir.get(Calendar.DAY_OF_YEAR);
            int birthYear = bir.get(Calendar.YEAR);
            Calendar eff = Calendar.getInstance();
            eff.setTime(effect);
            

            这基本上是对 John O 解决方案的修改,没有使用折旧的方法。我花了相当多的时间试图让他的代码在我的代码中工作。也许这会节省其他人的时间。

            【讨论】:

            • 你能解释清楚一点吗?这是如何计算年龄的?
            【解决方案15】:

            这个呢?

            public Integer calculateAge(Date date) {
                if (date == null) {
                    return null;
                }
                Calendar cal1 = Calendar.getInstance();
                cal1.setTime(date);
                Calendar cal2 = Calendar.getInstance();
                int i = 0;
                while (cal1.before(cal2)) {
                    cal1.add(Calendar.YEAR, 1);
                    i += 1;
                }
                return i;
            }
            

            【讨论】:

            • 这是一个非常可爱的建议(当您不使用 Joda 并且不能使用 Java 8 时)但是算法有点错误,因为在第一年的整个时间过去之前您都是 0。因此,您需要在开始 while 循环之前将日期添加到日期。
            【解决方案16】:

            String dateofbirth 有出生日期。格式是任意的(在下一行中定义):

            org.joda.time.format.DateTimeFormatter formatter =  org.joda.time.format.DateTimeFormat.forPattern("mm/dd/yyyy");
            

            格式如下:

            org.joda.time.DateTime birthdateDate = formatter.parseDateTime(dateofbirth );
            org.joda.time.DateMidnight birthdate = new         org.joda.time.DateMidnight(birthdateDate.getYear(), birthdateDate.getMonthOfYear(), birthdateDate.getDayOfMonth() );
            org.joda.time.DateTime now = new org.joda.time.DateTime();
            org.joda.time.Years age = org.joda.time.Years.yearsBetween(birthdate, now);
            java.lang.String ageStr = java.lang.String.valueOf (age.getYears());
            

            变量ageStr会有年份。

            【讨论】:

              【解决方案17】:

              优雅,看似正确,基于时间戳差异的 Yaron Ronen 解决方案变体。

              我包含了一个单元测试来证明它何时以及为什么不正确。由于(可能)在任何时间戳差异中闰日(和秒)的数量不同,这是不可能的。该算法的差异应该是最大 +-1 天(和一秒),请参阅 test2(),而基于 timeDiff / MILLI_SECONDS_YEAR 的完全恒定假设的 Yaron Ronen 解决方案对于 40 岁的人来说可能相差 10 天,但是这个变体是也不对。

              这很棘手,因为这个改进的变体使用公式 diffAsCalendar.get(Calendar.YEAR) - 1970,大部分时间都返回正确的结果,因为两个日期之间的平均闰年数相同。

              /**
               * Compute person's age based on timestamp difference between birth date and given date
               * and prove it is INCORRECT approach.
               */
              public class AgeUsingTimestamps {
              
              public int getAge(Date today, Date dateOfBirth) {
                  long diffAsLong = today.getTime() - dateOfBirth.getTime();
                  Calendar diffAsCalendar = Calendar.getInstance();
                  diffAsCalendar.setTimeInMillis(diffAsLong);
                  return diffAsCalendar.get(Calendar.YEAR) - 1970; // base time where timestamp=0, precisely 1/1/1970 00:00:00 
              }
              
                  final static DateFormat df = new SimpleDateFormat("dd.MM.yyy HH:mm:ss");
              
                  @Test
                  public void test1() throws Exception {
                      Date dateOfBirth = df.parse("10.1.2000 00:00:00");
                      assertEquals(87, getAge(df.parse("08.1.2088 23:59:59"), dateOfBirth));
                      assertEquals(87, getAge(df.parse("09.1.2088 23:59:59"), dateOfBirth));
                      assertEquals(88, getAge(df.parse("10.1.2088 00:00:01"), dateOfBirth));
                  }
              
                  @Test
                  public void test2() throws Exception {
                      // between 2000 and 2021 was 6 leap days
                      // but between 1970 (base time) and 1991 there was only 5 leap days
                      // therefore age is switched one day earlier
                          // See http://www.onlineconversion.com/leapyear.htm
                      Date dateOfBirth = df.parse("10.1.2000 00:00:00");
                      assertEquals(20, getAge(df.parse("08.1.2021 23:59:59"), dateOfBirth));
                      assertEquals(20, getAge(df.parse("09.1.2021 23:59:59"), dateOfBirth)); // ERROR! returns incorrect age=21 here
                      assertEquals(21, getAge(df.parse("10.1.2021 00:00:01"), dateOfBirth));
                  }
              }
              

              【讨论】:

                【解决方案18】:
                public class CalculateAge { 
                
                private int age;
                
                private void setAge(int age){
                
                    this.age=age;
                
                }
                public void calculateAge(Date date){
                
                    Calendar calendar=Calendar.getInstance();
                
                    Calendar calendarnow=Calendar.getInstance();    
                
                    calendarnow.getTimeZone();
                
                    calendar.setTime(date);
                
                    int getmonth= calendar.get(calendar.MONTH);
                
                    int getyears= calendar.get(calendar.YEAR);
                
                    int currentmonth= calendarnow.get(calendarnow.MONTH);
                
                    int currentyear= calendarnow.get(calendarnow.YEAR);
                
                    int age = ((currentyear*12+currentmonth)-(getyears*12+getmonth))/12;
                
                    setAge(age);
                }
                public int getAge(){
                
                    return this.age;
                
                }
                

                【讨论】:

                  【解决方案19】:
                  /**
                   * Compute from string date in the format of yyyy-MM-dd HH:mm:ss the age of a person.
                   * @author Yaron Ronen
                   * @date 04/06/2012  
                   */
                  private int computeAge(String sDate)
                  {
                      // Initial variables.
                      Date dbDate = null;
                      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      
                  
                      // Parse sDate.
                      try
                      {
                          dbDate = (Date)dateFormat.parse(sDate);
                      }
                      catch(ParseException e)
                      {
                          Log.e("MyApplication","Can not compute age from date:"+sDate,e);
                          return ILLEGAL_DATE; // Const = -2
                      }
                  
                      // Compute age.
                      long timeDiff = System.currentTimeMillis() - dbDate.getTime();      
                      int age = (int)(timeDiff / MILLI_SECONDS_YEAR);  // MILLI_SECONDS_YEAR = 31558464000L;
                  
                      return age; 
                  }
                  

                  【讨论】:

                  • 不确定你是否真的测试过这个,但是对于其他人来说,这个方法有一个缺陷。如果今天与您的出生日期是同一个月,并且今天
                  • 这不可能是真的,因为一年中的毫秒数不是恒定的。闰年多一天,比其他时间多得多。对于一个 40 岁的人,您的算法可能会提前 9 到 10 天报告生日,但确实如此!还有闰秒。
                  【解决方案20】:

                  这里是计算年、月、日年龄的java代码。

                  public static AgeModel calculateAge(long birthDate) {
                      int years = 0;
                      int months = 0;
                      int days = 0;
                  
                      if (birthDate != 0) {
                          //create calendar object for birth day
                          Calendar birthDay = Calendar.getInstance();
                          birthDay.setTimeInMillis(birthDate);
                  
                          //create calendar object for current day
                          Calendar now = Calendar.getInstance();
                          Calendar current = Calendar.getInstance();
                          //Get difference between years
                          years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
                  
                          //get months
                          int currMonth = now.get(Calendar.MONTH) + 1;
                          int birthMonth = birthDay.get(Calendar.MONTH) + 1;
                  
                          //Get difference between months
                          months = currMonth - birthMonth;
                  
                          //if month difference is in negative then reduce years by one and calculate the number of months.
                          if (months < 0) {
                              years--;
                              months = 12 - birthMonth + currMonth;
                          } else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
                              years--;
                              months = 11;
                          }
                  
                          //Calculate the days
                          if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
                              days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
                          else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
                              int today = now.get(Calendar.DAY_OF_MONTH);
                              now.add(Calendar.MONTH, -1);
                              days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
                          } else {
                              days = 0;
                              if (months == 12) {
                                  years++;
                                  months = 0;
                              }
                          }
                      }
                  
                      //Create new Age object
                      return new AgeModel(days, months, years);
                  }
                  

                  【讨论】:

                    【解决方案21】:

                    没有任何库的最简单方法:

                        long today = new Date().getTime();
                        long diff = today - birth;
                        long age = diff / DateUtils.YEAR_IN_MILLIS;
                    

                    【讨论】:

                    • 这段代码使用了麻烦的旧日期时间类,这些类现在是遗留的,被 java.time 类所取代。相反,请使用 Java 中内置的现代类:ChronoUnit.YEARS.between( LocalDate.of( 1968 , Month.MARCH , 23 ) , LocalDate.now() )。见correct Answer
                    • DateUtils 是一个图书馆
                    【解决方案22】:

                    使用Java 8,我们可以用一行代码计算一个人的年龄:

                    public int calCAge(int year, int month,int days){             
                        return LocalDate.now().minus(Period.of(year, month, days)).getYear();         
                    }
                    

                    【讨论】:

                    • 年龄是年还是月?一个月的宝宝怎么样?
                    【解决方案23】:
                    public int getAge(Date dateOfBirth) 
                    {
                        Calendar now = Calendar.getInstance();
                        Calendar dob = Calendar.getInstance();
                    
                        dob.setTime(dateOfBirth);
                    
                        if (dob.after(now)) 
                        {
                            throw new IllegalArgumentException("Can't be born in the future");
                        }
                    
                        int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
                    
                        if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) 
                        {
                            age--;
                        }
                    
                        return age;
                    }
                    

                    【讨论】:

                    • @sinuhepop 注意到“在处理闰年时,DAY_OF_YEAR 比较可能导致错误结果”
                    【解决方案24】:
                    import java.io.*;
                    
                    class AgeCalculator
                    {
                        public static void main(String args[])
                        {
                            InputStreamReader ins=new InputStreamReader(System.in);
                            BufferedReader hey=new BufferedReader(ins);
                    
                            try
                            {
                                System.out.println("Please enter your name: ");
                                String name=hey.readLine();
                    
                                System.out.println("Please enter your birth date: ");
                                String date=hey.readLine();
                    
                                System.out.println("please enter your birth month:");
                                String month=hey.readLine();
                    
                                System.out.println("please enter your birth year:");
                                String year=hey.readLine();
                    
                                System.out.println("please enter current year:");
                                String cYear=hey.readLine();
                    
                                int bDate = Integer.parseInt(date);
                                int bMonth = Integer.parseInt(month);
                                int bYear = Integer.parseInt(year);
                                int ccYear=Integer.parseInt(cYear);
                    
                                int age;
                    
                                age = ccYear-bYear;
                                int totalMonth=12;
                                int yourMonth=totalMonth-bMonth;
                    
                                System.out.println(" Hi " + name + " your are " + age + " years " + yourMonth + " months old ");
                            }
                            catch(IOException err)
                            {
                                System.out.println("");
                            }
                        }
                    }
                    

                    【讨论】:

                      【解决方案25】:
                      public int getAge(String birthdate, String today){
                          // birthdate = "1986-02-22"
                          // today = "2014-09-16"
                      
                          // String class has a split method for splitting a string
                          // split(<delimiter>)
                          // birth[0] = 1986 as string
                          // birth[1] = 02 as string
                          // birth[2] = 22 as string
                          // now[0] = 2014 as string
                          // now[1] = 09 as string
                          // now[2] = 16 as string
                          // **birth** and **now** arrays are automatically contains 3 elements 
                          // split method here returns 3 elements because of yyyy-MM-dd value
                          String birth[] = birthdate.split("-");
                          String now[] = today.split("-");
                          int age = 0;
                      
                          // let us convert string values into integer values
                          // with the use of Integer.parseInt(<string>)
                          int ybirth = Integer.parseInt(birth[0]);
                          int mbirth = Integer.parseInt(birth[1]);
                          int dbirth = Integer.parseInt(birth[2]);
                      
                          int ynow = Integer.parseInt(now[0]);
                          int mnow = Integer.parseInt(now[1]);
                          int dnow = Integer.parseInt(now[2]);
                      
                          if(ybirth < ynow){ // has age if birth year is lesser than current year
                              age = ynow - ybirth; // let us get the interval of birth year and current year
                              if(mbirth == mnow){ // when birth month comes, it's ok to have age = ynow - ybirth if
                                  if(dbirth > dnow) // birth day is coming. need to subtract 1 from age. not yet a bday
                                      age--;
                              }else if(mbirth > mnow){ age--; } // birth month is comming. need to subtract 1 from age            
                          }
                      
                          return age;
                      }
                      

                      【讨论】:

                      • 注意:日期格式为:yyyy-MM-dd。这是在 jdk7 中测试的通用代码...
                      • 如果您提供一些 cmets 或解释如何准确使用此代码,将会有所帮助。通常不鼓励简单的代码转储,提问者可能不理解您为什么决定以这种方式编写方法的原因。
                      • @rayryeng:Jhonie 已经在代码中添加了 cmets。这足以理解。在发表这样的评论之前请三思而后行。
                      • @Akshay 这对我来说并不明显。事后看来,他的代码似乎被抛弃了。我通常不读cmets。如果将它们从身体中取出并单独放置作为解释,那就太好了。这是我的偏好,我们可以同意在这里不同意....话虽如此,我忘记了我什至写了这个评论,因为它几乎是两年前。
                      • @rayryeng:这个评论背后的原因是,写负面的 cmets 会阻止人们使用这么好的论坛。因此,我们应该通过给予积极的 cmets 来鼓励他们。 Bdw,没有冒犯。干杯!!!
                      【解决方案26】:
                      import java.time.LocalDate;
                      import java.time.ZoneId;
                      import java.time.Period;
                      
                      public class AgeCalculator1 {
                      
                          public static void main(String args[]) {
                              LocalDate start = LocalDate.of(1970, 2, 23);
                              LocalDate end = LocalDate.now(ZoneId.systemDefault());
                      
                              Period p = Period.between(start, end);
                              //The output of the program is :
                              //45 years 6 months and 6 days.
                              System.out.print(p.getYears() + " year" + (p.getYears() > 1 ? "s " : " ") );
                              System.out.print(p.getMonths() + " month" + (p.getMonths() > 1 ? "s and " : " and ") );
                              System.out.print(p.getDays() + " day" + (p.getDays() > 1 ? "s.\n" : ".\n") );
                          }//method main ends here.
                      }
                      

                      【讨论】:

                      • 感谢您参与 StackOverflow。给你几个建议。 [A] 请在您的答案中加入一些讨论。 StackOverflow.com 不仅仅是一个代码 sn-p 集合。例如,请注意您的代码如何使用新的 java.time 框架,而大多数其他答案都使用 java.util.Date 和 Joda-Time。 [B] 请将您的答案与同样使用 java.time 的 Meno Hochschild 的 similar Answer 进行对比。解释你的更好或从不同的角度来解决这个问题。或者收回你的,如果不是更好的话。
                      【解决方案27】:
                      public int getAge(Date birthDate) {
                          Calendar a = Calendar.getInstance(Locale.US);
                          a.setTime(date);
                          Calendar b = Calendar.getInstance(Locale.US);
                          int age = b.get(YEAR) - a.get(YEAR);
                          if (a.get(MONTH) > b.get(MONTH) || (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
                              age--;
                          }
                          return age;
                      }
                      

                      【讨论】:

                        【解决方案28】:

                        感谢所有正确答案,但这是同一问题的 kotlin 答案

                        希望对 kotlin 开发者有所帮助

                        fun calculateAge(birthDate: Date): Int {
                                val now = Date()
                                val timeBetween = now.getTime() - birthDate.getTime();
                                val yearsBetween = timeBetween / 3.15576e+10;
                                return Math.floor(yearsBetween).toInt()
                            }
                        

                        【讨论】:

                        • 当我们拥有业界领先的 java.time 类可供我们使用时,这样做似乎相当愚蠢。
                        • Java 中的 OP 请求。
                        猜你喜欢
                        • 1970-01-01
                        • 2010-10-01
                        • 2010-09-05
                        • 2013-05-16
                        • 2019-04-17
                        • 1970-01-01
                        • 1970-01-01
                        • 2011-03-23
                        • 2014-12-14
                        相关资源
                        最近更新 更多