difference between dates in years

samadam
Mega Sage

I am trying to find difference between current date and start dates in years, this is in scoped applications. Datediff is not working. Any other ways to get this?

1 ACCEPTED SOLUTION

sunil maddheshi
Tera Guru

@samadam 

Please try below approach

var startDate = new GlideDateTime("2020-02-19"); // Replace with actual field value
var currentDate = new GlideDateTime();

var diffMillis = currentDate.getNumericValue() - startDate.getNumericValue();
var diffYears = diffMillis / (1000 * 60 * 60 * 24 * 365); 

gs.info("Difference in years: " + diffYears);

Please mark correct/helpful, thanks

View solution in original post

6 REPLIES 6

sunil maddheshi
Tera Guru

@samadam 

Please try below approach

var startDate = new GlideDateTime("2020-02-19"); // Replace with actual field value
var currentDate = new GlideDateTime();

var diffMillis = currentDate.getNumericValue() - startDate.getNumericValue();
var diffYears = diffMillis / (1000 * 60 * 60 * 24 * 365); 

gs.info("Difference in years: " + diffYears);

Please mark correct/helpful, thanks

V V Satyanaraya
Tera Contributor

hi @samadam 

 

please make use the below one:

https://www.servicenow.com/community/developer-forum/calculate-the-amount-of-days-between-two-dates/...

 

If my response helped please mark helpful

Nishant8
Tera Sage

Hello @samadam , You can use below script to get the result in days. Since you may not get the result always more than 365 days, its better of do a check and convert those days to years, if required. otherwise you can show the days:

var sgt1 = new GlideDate();
sgt1.setDisplayValue('2025-02-19');
var sgt2 = new GlideDate();
sgt2.setDisplayValue('2025-01-01');
var duration = GlideDate.subtract(sgt2,sgt1);
gs.info(duration.getDisplayValue());

Ankur Bawiskar
Tera Patron

@samadam 

try script shared by Sunil and share us the updates

If my response helped please mark it correct and close the thread so that it benefits future readers.