Calculate age by taking a date of type Date

Asked

Viewed 991 times

3

I’d like to calculate the age by taking the date of birth from the database, through the pojo.

I was looking at how to do a date calculation, looking at this question: Calculate age per day, month and year

My bank date is like DATE, then I could not convert to be able to compare with localDate, results this error:

(incompatible types: Date cannot be converted to Localdate)

I was trying to do like this:

 public int idade() {
    return Period.between(meuPojo.getDataNascimento(), LocalDate.now()).getYears();
}

my pojo method that picks up the date (getDataNascimento()) is the type java.util.Date;

How do I make this conversion?

1 answer

2


If you store the date in the format util.Date, need first convert to type Instant, which is the equivalent of util.Date in the package java.time. However, as well as Date, Instant represents a point in time, but without spindle information, and to convert to LocalDate, need this information. Then you inform a ZoneId(a representation of the zone of a given region), taking the spindle of the running system, to then convert to LocalDate:

Date birthday = new SimpleDateFormat("dd/MM/yyyy").parse("03/09/1990");

LocalDate ldirthday = birthday.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

System.out.println(Period.between(ldirthday, LocalDate.now()).getYears());

Testing on the same date of publication of this reply, resulted in:

26

See working on ideone.

In the case of your method, it would look like this:

 public int idade() {

    LocalDate ldirthday = meuPojo.getDataNascimento().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    return Period.between(ldirthday, LocalDate.now()).getYears();
}

I recommend reading of this answer on conversion and use of date classes of the new package java.time, which provides a fairly comprehensive explanation on the subject.


Reference:

Best way to Convert java.util.Date to java.time.Localdate in Java 8 - Examples

How to migrate from Date and Calendar to the new Java 8 Date API?

  • here he did not let use toLocalDate, because the getDataNascimento method is java.util.Date ?

  • @G.Araujo on the question you said it was java.sql.Date.

  • in the bank is Date, but I say the method. It is good to edit the question?

  • @G.Araujo certainly, the lack of this information induced my response.

  • edited the question !

  • 1

    @G.Araujo updated response.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.