How can I calculate age in Java accurately given Date of birth

扶醉桌前 提交于 2019-12-06 03:46:19

Below is an example of how to calculate a person's age, if today is their birthday, as well as how many days are left until their birthday if today is not their birthday using the new java.time package classes that were included as a part of Java 8.

  LocalDate today             = LocalDate.now();
  LocalDate birthday          = LocalDate.of(1982, 9, 26);
  LocalDate thisYearsBirthday = birthday.with(Year.now());

  long age = ChronoUnit.YEARS.between(birthday, today);

  if (thisYearsBirthday.equals(today))
  {
     System.out.println("It is your birthday, and your Age is " + age);
  }
  else
  {
     long daysUntilBirthday = ChronoUnit.DAYS.between(today, thisYearsBirthday);
     System.out.println("Your age is " + age + ". " + daysUntilBirthday + " more days until your birthday!");
  }

This is a code I use to figure out how old something is.

Long time= currentDate.getTime / 1000 - birthdate.getTime / 1000

int years = Math.round(time) / 31536000;
int months = Math.round(time - years * 31536000) / 2628000; 
Basil Bourque

The Answer by Nate is good. But it ignores the issue of time zone. And there is a more explicit approach possible.

Time Zone

Time zone is crucial in determining the date. For example, a new day dawns earlier in Paris than in Montreal.

If omitted, the JVM’s current default time zone is implicitly applied. I suggest you instead make explicit the time zone you expect/desire.

Use a proper time zone name, continent/city style. Never use the 3-4 letter codes such as "EST" or "IST".

java.time

The java.time framework (Tutorial) built into Java 8 and later includes the Periodclass to represent a span of time as a combined number of years, number of months, and number of days.

You can query a Period to extract each of those three components.

Period’s toString method by default generates a string in the format defined by ISO 8601, where a P marks the beginning followed by digit and letter three times. For example, one and a half years: P1Y6M.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
LocalDate birthdate = LocalDate.of( 1960 , 2 , 17 );
Period p = Period.between( birthdate , today );
String output = p.toString();
Integer age = p.getYears();
Boolean isTodayBirthday = ( (p.getMonths() == 0 )  && ( p.getDays() == 0 ) );

Another approach uses the MonthDay class to represent a month-day without a year.

Boolean isBirthdayToday = 
    MonthDay.from( birthdate )
            .equals( MonthDay.from( today ) ) ;

Android

For Android, you do not have Java 8 technology such as java.time.

You can search for some projects that backport java.time classes. I don't know how successful they are.

Also, you can use the Joda-Time, a third-party library that inspired the java.time framework (JSR 310). The Joda-Time code should be similar to the above. Except that the Period class has a finer resolution, going to hours, minutes, and seconds. To truncate that extra data, call the withTimeAtStartOfDay method.

This works for me.

Calendar currentDate = Calendar.getInstance();

SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

Date birthdate = null;

try {
     birthdate = myFormat.parse(yourDate);
} catch (ParseException e) {
     e.printStackTrace();
}

Long time= currentDate.getTime().getTime() / 1000 - birthdate.getTime() / 1000;

int years = Math.round(time) / 31536000;
int months = Math.round(time - years * 31536000) / 2628000;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!