Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to calculate years based on the two date fields

Aditya Banka2
Tera Guru

Hello Geeks,

I have a field called as Purchased Date in asset table where in the date shows as something like 2021-02-12 10:30:00.

I have created a new integer field to calculate the age of the asset in years based on the current date - purchased date which gets updated using a schedule job on a monthly basis.

Below is the script

var gr = new GlideRecord('alm_hardware');
gr.addEncodedQuery('serial_number=BQP-854-D33246-GH');
gr.query();
while (gr.next())
{

var cur = new GlideDateTime();
gs.log('cur: '+cur);
var pur = new GlideDateTime(gr.install_date);
gs.log('pur: '+pur);
var diffSeconds = gs.dateDiff(pur.getDisplayValue(), cur.getDisplayValue(), true);
gs.log('Difference: '+diffSeconds);
var inYears=diffSeconds /(60*60*24*365);
gs.log('Years: '+inYears);

gr.u_device_age_years = inYears;
gr.update();

}

 

*** Script: cur: 2022-05-06 18:37:46
*** Script: pur: 2018-05-25 07:00:00
*** Script: Difference: 124630666
*** Script: Years: 3.9520124936580414

as you see from the output, When I update the record, it is getting updated as 4 instead of 3.
*** Script: Years: 3.3656024543378997, If the value is anything less that 3.5 then it is getting updated as 3.

I need to discard all the decimal values before I update the field.



 

 

1 ACCEPTED SOLUTION

Aditya Banka2
Tera Guru

I have used below code which worked fine.

 

var cur = new GlideDateTime();
    var pur = new GlideDateTime(gr.u_purchase_date);
    var dur = new GlideDuration(GlideDateTime.subtract(pur, cur));
    var inYears = dur.getDayPart() / 365;
    var Years = parseInt(inYears);

View solution in original post

5 REPLIES 5

@Aditya Banka 

I see you have followed the solution that I had proposed?
Is there a reason, you didn't mark it as helpful or correct?

 

Best Regards
Aman Kumar