Calculate difference in date field in years
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-20-2016 02:03 AM
I have two fields which are date type (note date/time).
I want to get the difference in years. I am not able to find any function which gives result in years?
Can someone suggest?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-20-2016 02:11 AM
Hi Anupama,
Please use the subtract function .Check the below link (section 3.64.3 for example) ...I hope the dates are GlideDateTime object...
GlideDateTime.subtract...
It will not give answer in years you will have to convert the result you get from it like divide by 365*24*3600
GlideDateTime - ServiceNow Wiki
Mark Correct if it solved your issue or hit Like and Helpful if you find my response worthy.
Thanks,
Deepa
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-20-2016 02:12 AM
Hi,
Here is an example, which will give difference in terms of seconds between 2 variables, say nowTs and ts. You can convert this into your own logic.
var d=new Date(); // Gets the current time
var nowTs = Math.floor(d.getTime()); // getTime() returns milliseconds, and we need seconds, hence the Math.floor and division by 1000
var seconds = (nowTs/1000)-(ts/1000);
if (seconds > 365*24*3600) {
return Math.floor(seconds/(365*24*3600)) + " Year(s) ago";
}

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-20-2016 02:14 AM
Hi Anupama,
You can use dateDiff() method of GlideSystem class.For example
var date1 = new GlideDateTime('2014-01-01');
var date2 = new GlideDateTime('2015-01-01');
var diffSeconds = gs.dateDiff(date1.getDisplayValue(), date2.getDisplayValue(), true);
gs.log('Difference: '+diffSeconds);
var inYears=diffSeconds /(60*60*24*365);
gs.log('Years: '+inYears);
Refer below link
GlideSystem Date and Time Functions - ServiceNow Wiki
Thanks,
Abhinandan

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-20-2016 02:54 AM
Hi,
Refer the below code for your reference.
var date1 = new GlideDateTime();
var date2 = new GlideDateTime();
date1.setDisplayValueInternal('2014-01-01 12:00:00');
date2.setDisplayValueInternal('2019-03-01 13:00:00');
var diffSeconds = gs.dateDiff(date1.getDisplayValue(), date2.getDisplayValue(), true);
var years=Math.floor(diffSeconds/(365*24*3600));
gs.print(years);
Hope it helps.