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 ?
– JavaTech
@G.Araujo on the question you said it was java.sql.Date.
– user28595
in the bank is Date, but I say the method. It is good to edit the question?
– JavaTech
@G.Araujo certainly, the lack of this information induced my response.
– user28595
edited the question !
– JavaTech
@G.Araujo updated response.
– user28595