0

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!

Gordon Mohrin
  • 645
  • 1
  • 6
  • 17
Dave
  • 1,257
  • 2
  • 27
  • 58
  • Well i would write 'my own division', you can create array with 12 months (containint amount of days ofc) and just subtract them in a loop. That might be a poor solution thou. Every fourth year just change amount for February. – Tomal Mar 12 '19 at 21:01

2 Answers2

0

Using this answer as a reference.

Basically it calculates the number of leap years before each date's year value, then subtracts the result of the earlier date from the later.

Once you have that number, you can add that many days to your day count.

// ... the rest of your code

var durationDays = Math.floor((duration % 365)%30) + LeapYearsBetween(fromYearValue, toYearValue);

function LeapYearsBetween(start, end)
{
    return LeapYearsBefore(end) - LeapYearsBefore(start + 1);
}

function LeapYearsBefore(year)
{
    year -= 1;
    return (year / 4) - (year / 100) + (year / 400);
}

Hope this points you in the right direction.

Thomas Prince
  • 332
  • 1
  • 5
0

for Month and Years just calculate with gdt.getMonth() and gdt.getYear() and add 12 Months, if they are years apart.

years: gdt1.getYear() - gdt2.getYear()

Months gdt1.getMonth() - gdt2.getMonth() + yearDifference*12

Days should be correct as far as I can see. You can check this thread too Difference in Months between two dates in JavaScript

Gordon Mohrin
  • 645
  • 1
  • 6
  • 17