In the employee master, I added a custom field called “age”, and I want the employee’s age to be calculated within this field, based on the “Date of Birth” field in the master.
Please, can someone help me with the Python code that achieves this?
Thanks for your time in advance…
You can develop using both side, server and client.
client script:
frappe.ui.form.on('Employee', {
date_of_birth: function(frm) {
var dob = frm.doc.date_of_birth;
if (dob) {
var today = new Date();
var birthDate = new Date(dob);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
frm.set_value('age', age);
}
}
});
Server side:
import datetime
def calculate_age(doc, method):
if doc.date_of_birth:
today = datetime.date.today()
dob = doc.date_of_birth
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
doc.age = age