简体   繁体   中英

Calculate AGE between two java.Util.Date

Folks!

Could any one help me find the way out this situation? I'm aware that java.util.Date is deprecated, but my work is all based on it.

I'm having trouble to return the age in Years from the User. I have these two dates:

        Date nascimento = dashboard.getDtNascimento();
        Date creationTime = new Date(session.getCreationTime());

That first Date come from a ArrayList that contains the user BirthDay. The second one come from the user session..

How can I return the age having those two Dates? How can I do the math? Is that any kind of way to parse those Dates into LocalDate perhaps...

Thank you guys!

Yes, you can convert these to LocalDate like this...

Date creationTime = new Date(session.getCreationTime());
LocalDate localCreationTime = creationTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

If I understand your question you want to find the difference between these dates?

If you convert to LocalDate you can do this:

long age = YEARS.between(localNascimento, localCreationTime);

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 LocalDate s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM