Calculate age by taking a date of type Date

3

I would like to calculate the age by taking the date of birth from the database, using pojo .

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

My date in the database is as DATE , so I could not convert to be able to compare with localDate, this error results:

  

(Incompatible types: Date can not be converted to LocalDate)

I was trying to do this:

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

My pojo method that takes the date ( getDataNascimento() ) is of type java.util.Date ;

How do I do this conversion?

    
asked by anonymous 06.08.2017 / 03:18

1 answer

2

If you store the date in util.Date format, you must first convert to Instant ", which is the equivalent of util.Date in the package java.time . However, just like Date , Instant represents a point in time but no spindle information, and to convert to LocalDate , you need this information. Then you inform a ZoneId (a representation of the given spindle region), taking the running system spindle, then converting 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 as this response was published, resulted in:

  

26

See working at 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 this answer about converting and using date classes from the new java.time package, which gives a fairly comprehensive explanation of the topic.

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 date API in Java 8?

    
06.08.2017 / 04:56