We have a requirement in our scoped ServiceNow application to calculate the number of Years, Months, and Days between 2 dates. Our Business Rule below works fine, but it's not 100% perfect:
(function executeRule(current, previous /*null when async*/) {
var t = new GlideDateTime(current.from.getDisplayValue());
var f = new GlideDateTime(current.to.getDisplayValue());
var duration = GlideDateTime.subtract(t, f).getDayPart();
var durationYears = Math.floor(duration/365);
var durationMonths = Math.floor((duration % 365)/30);
var durationDays = Math.floor((duration % 365)%30);
current.setValue('year', durationYears);
current.setValue('month', durationMonths);
current.setValue('day', durationDays);
})(current, previous);
This works fine if the assumption is there are 30 days in each month. However, month lengths can obviously be anywhere between 29 - 31 days (including leap years). Any suggestions on the above code can be more accurate without using libraries such as moment.js?
Thanks!