Calculate Age based on a choice field "Year" in hardware asset

zcambayot06
Tera Contributor

Hi Snow Community,

 

I have a choice field in asset table called "Year" - choices are from (1990-current year). Now, I created a new field, 'u_age' with string type. I want to get the value of 'Age' by getting the today's date minus the 'Year' field. 

For example, Year is 2000, Age will be 24 Years. I have tried creating a display BR but im not getting anywhere. Have search OOTB like for Incident, but the type used is duration. Below sample OOTB.

 

Display BR

current.u_age=gs.dateDiff(current.sys_created_on.getDisplayValue(),gs.nowDateTime());
 
Any help will be appreciated. Thank you.
4 REPLIES 4

zcambayot06
Tera Contributor

Just an update. I tried following a solution wherein, I created a script include and client script to calculate the value.

However, it displays NAN value. I'm stuck here. Anyone can help? Thank you.

 

Script include:

var assetAgecalculator = Class.create();
assetAgecalculator.prototype = Object.extendsObject(AbstractAjaxProcessor, {

checkAge: function() {
var year = this.getParameter('sysparam_id');//param from client script
var today = new GlideDateTime();
var todayYear = today.getYearLocalTime();
var asset = new GlideDateTime(year.toString());
var assetYear = bday.getYearLocalTime();
var age = todayYear - assetYear;
return age;
},

type: 'assetAgecalculator'
});
 
Client script:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
 var ga = new GlideAjax('assetAgecalculator');
    ga.addParam('sysparm_name', 'checkAge');
    ga.addParam('sysparam_id', newValue);
    ga.getXML(Process);
}

function Process(response) {
    var answer = response.responseXML.documentElement.getAttribute("answer");
    alert(answer);
    var a = parseInt(answer);
    alert(a);
    g_form.setValue("u_age", a);
}

nowitsvashu
Tera Guru
// Get the current year
var currentYear = new GlideDateTime().getYearLocalTime();

// Parse the "Year" field to integer, assuming it's stored as a string
var assetYear = parseInt(current.getValue('Year'), 10);

if (!isNaN(assetYear) && assetYear <= currentYear) {
    // Calculate the age
    var age = currentYear - assetYear;
    current.u_age = age + " Years";
} else {
    // Handle any invalid or future year cases
    current.u_age = "Invalid Year";
}

Hi nowitsvashu,

 

thanks for the response. Just wanted to confirm if this is on client script only that I need to update? or script include as well? 

Thanks!

Have tried you suggestion but still showing NAN/null value.