Home > database >  Find the minimum birthdate of people based on a given age?
Find the minimum birthdate of people based on a given age?

Time:12-20

In my app, I want to filter data based on age range. The problem is that I didn't store the age in the database so I have to use the birthdate.

This is what I did so far but it's incorrect:

public String getDOBFromAge(int age){
    LocalDate today = LocalDate.now();
    LocalDate ld = today.minusYears(age);
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    return ld.format(dtf);
}

When I have age=23, it gives me an output of 1999-12-20. I am 23 years old as of 2022-12-20 but my birthdate is 1999-11-24. So my solution is lacking something. Can anyone please help me?

CodePudding user response:

Let's say you're 23 years old. For example, a person who is 23 years old can have an age that ranges from 23 years 0 days to 23 years 364 days. In this range of days, the age will be 23 years. So the minimum birthday is for someone who is 23 years and 364 days.

The below will let you find that:

public static String getDOBFromAge(int age){
    LocalDate today = LocalDate.now();
    LocalDate ld = today.minusYears(age 1);
    ld = ld.plusDays(1);
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    return ld.format(dtf);
}
  • Related