Home > OS >  Java - How to calculate age by considering birthday date on database
Java - How to calculate age by considering birthday date on database

Time:06-27

I'm trying to solve this problem but i can't find a good solution. When an user register on my website, among other data, I'm asking for the birthday date. As well as the birthday date, I'd also like to add on the database the actual age of the user so, in order to do that, I'm using this code (added into the class User.java):

private LocalDate dateOfBirth;

private int actualAge = ageCalculator(dateOfBirth);

public int ageCalculator(LocalDate data) {
    LocalDate d = LocalDate.now();
    if(data != null) {
        return Period.between(data, d).getYears();
    }else {
        return //error message;
    }
}

The problem is that this code, is working just in the right moment an user register on the website. For example: let's say tomorrow I'll turn 30 and I register on the website today (that I'm still 29). So, on the database will be added the age "29". But tomorrow, that I'll turn 30, the age on the database will still be 29. There is a way to automatically update the age? I was thinking about to get the birthday date of every user with a Query - by month - and update the age. Let me explain better: now we are in June, so with the query I'll select all the users who were born in June and if the month and the day of their birthday is the same to the month and day of the LocalDate.now(), then I increase the age by 1. Do you have any suggestion? Thanks for the help/advices.

CodePudding user response:

You should not store the age because is always changing. Age should be calculated every time you query persons information. You already have a solution in Java, you could also do it using SQL.

CodePudding user response:

I wrote this a bunch of years ago in FoxPro, but you should be able to follow the logic

function get_age
parameters dob_in

private m.age_

m.age_ = year(m.GItoday) - year(dob_in)

do case
    case month(dob_in) > month(m.GItoday) 
        m.age_ = m.age_ - 1

    case month(dob_in) = month(m.GItoday)
        if day(dob_in) > day(m.GItoday)
            m.age_ = m.age_ - 1
        endif
    
endcase

return m.age_

You have to consider not only the year, but also the month, then the day.

  • Related