【问题标题】:ServiceNow: Calculating date diff in Years, Months, Days not accurateServiceNow:计算年、月、日的日期差异不准确
【发布时间】:2019-08-03 10:55:44
【问题描述】:

我们在范围内的 ServiceNow 应用程序中要求计算两个日期之间的年数、月数和天数。我们的以下业务规则运行良好,但并非 100% 完美:

    (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);

如果假设每个月有 30 天,这很好用。但是,月份长度显然可以在 29 到 31 天之间(包括闰年)。以上代码有什么建议可以不使用moment.js等库更准确?

谢谢!

【问题讨论】:

  • 好吧,我会写“我自己的除法”,您可以创建 12 个月的数组(包含天数),然后在循环中减去它们。这可能是一个糟糕的解决方案。每四年只需更改 2 月的金额。

标签: javascript datediff servicenow


【解决方案1】:

对于月份和年份,只需使用 gdt.getMonth() 和 gdt.getYear() 计算并添加 12 个月,如果它们相隔年份。

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

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

据我所知,天数应该是正确的。你也可以查看这个帖子Difference in Months between two dates in JavaScript

【讨论】:

    【解决方案2】:

    使用this answer 作为参考。

    基本上它计算每个日期的年份值之前的闰年数,然后从较晚的日期中减去较早日期的结果。

    一旦你有了这个数字,你就可以在你的天数中加上那么多天。

    // ... 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);
    }

    希望这会为您指明正确的方向。

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      相关资源
      最近更新 更多