Salini
Salini

Reputation: 347

In java age calculate returns wrong value

In java I want to calculate age..

I am using "jodatime.jar"

LocalDate today = LocalDate.now();
LocalDate birthdate = new LocalDate ("1990-12-12");
Years age = Years.yearsBetween(birthdate, today);

I want age as integer..here it returns value like P25Y..How to get integer value of age..I want just 25

Is there any other way to get age in java with date format..In google I have tried a lot but not found any proper example which use date format

Upvotes: 2

Views: 260

Answers (5)

RockAndRoll
RockAndRoll

Reputation: 2277

Using joda-time

You can use Period to achieve this available in joda time api. Try something like this:

Period period = new Period(d1, d2);// d1,d2 are Date objects
System.out.print("You are " + period.getYears() + " years old");

Using java.time

If you can go Java 8 or later with the java.time classes LocalDate and Period, then it can be achieved like this:

        LocalDate today = LocalDate.now();
        LocalDate birthday = LocalDate.of(1990, Month.DECEMBER, 12);

        Period p = Period.between(birthday, today);
        System.out.println("You are " + p.getYears() + " years old");

Output

You are 25 years old

Upvotes: 5

Mukesh
Mukesh

Reputation: 182

Use age.getYears() to get the int value of age.

Upvotes: 4

Irina Avram
Irina Avram

Reputation: 1522

If you want to keep yousing jodattime, you should know, it has a method for getting the number of year: .getYears()

If you just want to get the age then use Gregorian calendar to get the year and compare it to the current one:

Calendar date = new GregorianCalendar(2012, 9, 5);
int birthyear = date.get(Calendar.YEAR); // 2012
Date currdate = new Date();
Calendar date2 = new GregorianCalendar();
date2.setTime(currdate);
int curryear = date.2get(Calendar.YEAR); // current year(2015 atm)

Upvotes: 0

Raphaël
Raphaël

Reputation: 3726

age is not an Integer but a Years. If you want to retrieve the age as an integer, use the getYears() method:

int age = Years.yearsBetween(birthdate, today).getYears();

Upvotes: 0

ThomasThiebaud
ThomasThiebaud

Reputation: 11969

You can use age.getYears(). From the doc

Gets the number of years that this period represents.

Upvotes: 0

Related Questions