How to Calculate Someone'S Age in Java

How do I calculate someone's age in Java?

JDK 8 makes this easy and elegant:

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;
}
}
}

A JUnit test to demonstrate its use:

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);
}
}

Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.

Program in JAVA to calculate age of person from birthdate and current date

Time calculations are tricky beasts, and it's best to avoid implementing custom Date/Time classes (except maybe for exercise or learning purposes). As for your question, use Java 8's java.time.* classes:

ZoneId timeZoneId = ZoneId.of("Europe/Warsaw"); // assuming you're in Poland - put the your time zone name here ;-)
LocalDate today = LocalDate.now(timeZoneId);
LocalDate birthday = LocalDate.of(year, month, day);
Period lifePeriod = Period.between(birthday, today);
long age = lifePeriod.getYears();

As for the GUI part of your question - it's "a bit" too broad :-) As a general advice - learn about JavaFX, and how to build UIs in it, if you want to use Java as your toolkit for GUI apps.

EDIT: Side note on codestyle and conventions - Java has a well established method and variable naming conventions - it's always a good practice to learn and use them. It makes your code more readable for those familliar with the conventions.

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

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!");
}

Calculate AGE between two java.Util.Date

You can get an Instant from java.util.Date. From the Instant, you can get an OffsetDateTime and from that, you can get a LocalDate. Finally, you can use Period.between to get Period between the LocalDates and from the Period, you can get years.

Demo:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.util.Date;

public class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = sdf.parse("1975-08-27");
Date endDate = sdf.parse("2020-02-15");

OffsetDateTime startOdt = startDate.toInstant().atOffset(ZoneOffset.UTC);
OffsetDateTime endOdt = endDate.toInstant().atOffset(ZoneOffset.UTC);

int years = Period.between(startOdt.toLocalDate(), endOdt.toLocalDate()).getYears();
System.out.println(years);
}
}

Output:

44

Calculate age from BirthDate

Here is a Java method called getAge which takes integers for year month and day and returns a String type which holds an integer that represents age in years.

private String getAge(int year, int month, int day){
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();

dob.set(year, month, day);

int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}

Integer ageInt = new Integer(age);
String ageS = ageInt.toString();

return ageS;
}

How to calculate age from D.O.B?

Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).

Java 8 has something very similar and is worth checking out.

e.g.

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

which is as simple as you could want.

Great examples for using dates with Java 8: Java 8 Date Examples

Happy Coding!

How do I calculate someone's age based on a DateTime type birthday?

An easy to understand and simple solution.

// Save today's date.
var today = DateTime.Today;

// Calculate the age.
var age = today.Year - birthdate.Year;

// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;

However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.

Calculate age in java considering leap years

The correct way to do this is with the Period and LocalDate classes in the java.time package. However, it seems that you're trying to reinvent the calculation for yourself.

The way that I would recommend doing this is to write a class that lets you calculate a "day number" for a given date - that is, the number of days between the specified date, and some arbitrary date in the past. Then when you want to find the number of days between two specified dates, you can just use calculate the "day number" for both dates, and subtract them.

I have done that here, for a purely Gregorian calendar. This class is no good before the Gregorian cutover - I haven't tried to build a historically accurate Julian/Gregorian hybrid calendar, such as the JDK provides. And the arbitrary date in the past that it calculates day numbers from is 31 December, 2BC. This date, of course, isn't really part of the Gregorian calendar; but for our purposes here, it doesn't matter.

Since you're unlikely to encounter any dates before the Gregorian cutover, this class should be more than adequate for your purposes. I still recommend using the Period and LocalDate classes instead of this one, for production code. This is just here so you can see how to do the calculations.

public class GregorianDate {

private final int day;
private final int month;
private final int year;

private static final int[] DAYS_PER_MONTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

public GregorianDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}

public boolean isValid() {
return month >= 1 && month <= 12 && day >= 1 && day <= daysThisMonth();
}

public static int daysBetween(GregorianDate from, GregorianDate to) {
return to.dayNumber() - from.dayNumber();
}

public static int daysBetween(int fromDay, int fromMonth, int fromYear, int toDay, int toMonth, int toYear) {
return daysBetween(new GregorianDate(fromDay, fromMonth, fromYear), new GregorianDate(toDay, toMonth, toYear));
}

private int daysThisMonth() {
return (isLeapYear() && month == 2) ? 29 : DAYS_PER_MONTH[month];
}

private int dayNumber() {
return year * 365 + leapYearsBefore() + daysInMonthsBefore() + day;
}

private boolean isLeapYear() {
return ( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0;
}

private int leapYearsBefore() {
return year / 4 - year / 100 + year / 400;
}

private int daysInMonthsBefore() {
switch(month) {
case 1:
return 0;
case 2:
return 31;
default:
// Start with the number in January and February combined
int toReturn = isLeapYear() ? 60 : 59;
for (int monthToConsider = 3; monthToConsider < month; monthToConsider++) {
toReturn += DAYS_PER_MONTH[monthToConsider];
}
return toReturn;
}
}

}


Related Topics



Leave a reply



Submit