How can we calculate Duration in years and months

Raj90
Tera Guru

Hi,

Contract duration should be equal toExpiry date – Effective date(start date)”.

Duration should be in years such as 2 years and 6 months

find_real_file.png

 

Thanks 

Raj

9 REPLIES 9

Alberto Consonn
ServiceNow Employee
ServiceNow Employee

Hi,

please refer to the following thread, it will help you to do it easily:

https://stackoverflow.com/questions/55130458/servicenow-calculating-date-diff-in-years-months-days-n...

I would also suggest you to check the following ServiceNow thread as well, there are some other interesting good idea:

https://community.servicenow.com/community?id=community_question&sys_id=e57f3ea9db58dbc01dcaf3231f96...

If I have answered your question, please mark my response as correct so that others with the same question in the future can find it quickly and that it gets removed from the Unanswered list.

Thank you

Cheers
Alberto

I tried in the below one,but it's not working

var gr=new GlideRecord('u_contract');
gr.query();
while(gr.next()){
duration = gs.dateDiff(gr.current.u_expiry_date.getGlideObject().getDisplayValue(),gr.current.u_effective_date.getGlideObject().getDisplayValue(), true);

var durationYears = Math.floor(duration/365);
var durationMonths = Math.floor((duration % 365)/30);
var durationDays = Math.floor((duration % 365)%30);


template.print("Duration:" + durationYears + 'Years'+durationMonths+ 'Months');

}

 

Thanks

Try to put some log and share what is the outcome please.

I'm getting in the below way:

Code:

var gr=new GlideRecord('u_contract');
gr.query();
while(gr.next()){
var duration = gs.dateDiff(gr.u_expiry_date.getGlideObject().getDisplayValue(),gr.u_effective_date.getGlideObject().getDisplayValue(), true);

var durationYears = Math.floor(duration/365);
var durationMonths = Math.floor((duration % 365)/30);
var durationDays = Math.floor((duration % 365)%30);


gs.log("Duration:"+durationYears + " "+'Years'+ " "+durationMonths+ " "+'Months');

}

O/P:-

find_real_file.png