Alternative to gs.dateDiff for scoped app?

Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-09-2022 05:41 PM
I have a requirement to set the calculated value of a string field in a scoped app by comparing a form field's date and the current date to display in the string field as "x Years, x Month(s)". Below is the code that is working in Global, but not sure how to do the same thing in a scoped app with GlideDateTime.subtract(). Any suggestions are appreciated.
(function calculatedFieldValue(current) {
var diff = gs.dateDiff(current.date_of_birth, new GlideDateTime(), true);
function getDurationAsString(maxUnits, seconds) {
var units = [],
data = [{
"l": "Year",
"s": 31535000
}, {
"l": "Month",
"s": 2628000
}, {
"l": "Day",
"s": 86400
}, {
"l": "Hour",
"s": 3600
}, {
"l": "Minute",
"s": 60
}, {
"l": "Second",
"s": 1
},
];
for (var i = 0; i < data.length && i < maxUnits; i++) {
if (seconds >= data[i].s) {
var unit = Math.floor(seconds / data[i].s);
seconds -= (unit * data[i].s);
units.push(unit + ' ' + data[i].l + ((unit == 1) ? '' : 's'));
}
}
return units.join(', ');
}
return getDurationAsString(2, diff);
})(current);
Labels:
2 REPLIES 2
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-09-2022 07:04 PM
Hi
use this:
var diff = GlideDateTime.subtract(new GlideDateTime(), current.date_of_birth);
Kind regards
Maik

Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-09-2022 08:12 PM
Try:
var gdt1 = new GlideDateTime();
var gdt2 = new GlideDateTime(current.date_of_birth);
var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2
data = [{
"l": "Year",
"s": 'yyyy'
}, {
"l": "Month",
"s": 'MM'
}, {
"l": "Day",
"s": 'dd'
}, {
"l": "Hour",
"s": 'hh'
}, {
"l": "Minute",
"s": 'MM'
}, {
"l": "Second",
"s": 'ss'
}, ];
var units = [];
for (var i = 0; i < data.length; i++) {
var unit = dur.getByFormat(data[i].s);
unit = parseInt(unit);
if (data[i].l == 'Year') {
unit = unit - 1970;
}
if (unit != 0) {
units.push(unit + ' ' + data[i].l + (unit < 2 ? '' : 's'));
}
}