Java从出生日期算起年龄

为了从诞生之日起计算时代,任何人似乎真的简单的事,它确实是。从广义上讲,我可以将此年龄计算器程序的三个解决方案可视化。

目录

1。 Java 8 Period类[最佳] 
2。 Jodatime库[良好] 
3.日期和日历类[基本]

1.从出生日期算起年龄-Java 8 Period类

Java 8程序,用于从出生日期开始计算一个人的年龄。它使用Period类存储两个LocalDate实例之间的差异。这两个日期是今天的日期和出生日期。

一旦Period类被创建,我们可以得到所需的指标两个日期之间的差值。

LocalDate today = LocalDate.now();							//Today's date
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1); 	//Birth date

Period p = Period.between(birthday, today);

//Now access the values as below
System.out.println(period.getDays());
System.out.println(period.getMonths());
System.out.println(period.getYears());

2.从出生日期算起年龄-Jodatime图书馆

我们知道,新的Java 8日期时间API受到Joda库的启发。Joda还具有Period与Java 8 Period类非常相似的类。

因此,该解决方案也与Java 8解决方案非常相似。

LocalDate birthdate = new LocalDate (1970, 1, 20); 		//Birth date
LocalDate now = new LocalDate();						//Today's date

Period period = new Period(birthdate, now, PeriodType.yearMonthDay());

//Now access the values as below
System.out.println(period.getDays());
System.out.println(period.getMonths());
System.out.println(period.getYears());

上面两个示例之间的唯一区别是方法“ between”Period在Joda库的类中不可用。在Java 8中,Period类用于定义具有基于日期的值(年,月,日)的时间。

3.用日期和日历计算年龄

该解决方案是非常基础的,应仅用于学习计算逻辑。对于生产级软件,我不建议使用此方法。尽管它可以正常工作,但是代码看起来不太易读,性能(无法准确衡量)也可能是不利的一面。

通过添加Age类使该解决方案看起来更专业,我付出了一些努力。😉

我已经设置了默认的构造函数,private并提供了constructor接受天,月,年的。我们还可以添加参数验证,以使其不接受负值。

class Age
{
   private int days;
   private int months;
   private int years;

   private Age()
   {
      //Prevent default constructor
   }

   public Age(int days, int months, int years)
   {
      this.days = days;
      this.months = months;
      this.years = years;
   }

   public int getDays()
   {
      return this.days;
   }

   public int getMonths()
   {
      return this.months;
   }

   public int getYears()
   {
      return this.years;
   }

   @Override
   public String toString()
   {
      return years + " Years, " + months + " Months, " + days + " Days";
   }
}

第二类AgeCalculator本身具有private接受人的出生日期并返回Age具有人的年龄信息的实例的方法。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AgeCalculator
{
   private static Age calculateAge(Date birthDate)
   {
      int years = 0;
      int months = 0;
      int days = 0;

      //create calendar object for birth day
      Calendar birthDay = Calendar.getInstance();
      birthDay.setTimeInMillis(birthDate.getTime());

      //create calendar object for current day
      long currentTime = System.currentTimeMillis();
      Calendar now = Calendar.getInstance();
      now.setTimeInMillis(currentTime);

      //Get difference between years
      years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
      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;
         if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
            months--;
      } 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 Age(days, months, years);
   }

   public static void main(String[] args) throws ParseException
   {
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
      Date birthDate = sdf.parse("29/11/1981"); 	
      Age age = calculateAge(birthDate);
      System.out.println(age);
   }
}

程序输出。

32 Years, 5 Months, 27 Days

让我知道您对上述解决方案的想法,这些解决方案可以用Java从出生日期算起年龄

saigon has written 1445 articles

Leave a Reply