here we know the birth date of the user (birth_date) and we want to calculate his age so let's do it
- add the birth date field and age field in your model as
birth_date = fields.Date(string="Birth Date")
age_year = fields.Float(string="Years", compute='calculate_age')
age_month = fields.Float(string="Months", compute='calculate_age')
age_day = fields.Float(string="Days", compute='calculate_age')
- the add calculate_age() function to calculate the age and store it in age field
@api.one
def calculate_age(self):
def calculate_age(self):
"""
function to calcolate the age of he user
"""
if self.birth_date :
birth_date = str(self.birth_date)
current_date = str(fields.Date.today())
birth_date_year_as_int = int(birth_date[0]+birth_date[1]+birth_date[2]+birth_date[3])
birth_date_month_as_int = int(birth_date[5]+birth_date[6])
birth_date_day_as_int = int(birth_date[8]+birth_date[9])
current_date_year_as_int = int(current_date[0]+current_date[1]+current_date[2]+current_date[3])
current_date_month_as_int = int(current_date[5]+current_date[6])
current_date_day_as_int = int(current_date[8]+current_date[9])
period_years = current_date_year_as_int-birth_date_year_as_int
period_months = current_date_month_as_int-birth_date_month_as_int
period_days = current_date_day_as_int-birth_date_day_as_int
months_list_1 = ['04','06','09','11']
months_list_2 = ['01','03','05','07','08','10','12']
if period_days < 0:
if str(current_date_month_as_int) == '02':
if current_date_year_as_int%4 == 0:
period_days = 29+period_days
if current_date_year_as_int%4 != 0:
period_days = 28+period_days
for index in range(0,4):
if current_date_month_as_int == int(months_list_1[index]):
period_days = 30+period_days
for index in range(0,7):
if current_date_month_as_int == int(months_list_2 [index]):
period_days = 31+period_days
period_months = period_months-1
if period_months < 0:
period_months = 12+period_months
period_years = period_years-1
self.age_year = period_years
self.age_month = period_months
self.age_day = period_days
No comments:
Post a Comment