Custom field in Employee Master to calculate employee age

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…

Hi,

You should be able to use a api call like:
frappe.get_value(“Employee”, “HR-EMP-00001”, “date_of_birth”)

and the python datetime module to get today or some other date and subtract…
datetime,date.today()

There are tutorials or date arithmetic in python on the web, ie:
https://www.dataquest.io/blog/python-datetime/

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