← Script library

Script Includes

Date Calculation Utility

Reusable functions for common date and time calculations, business days, and formatting.

JavaScript
var DateCalculator = Class.create();
DateCalculator.prototype = {

  /**
   * Add business days to a date
   * @param {GlideDateTime} startDate - Starting date
   * @param {number} days - Number of business days to add
   * @param {string} scheduleId - Schedule sys_id or name (optional)
   * @returns {GlideDateTime} Resulting date
   */
  addBusinessDays: function(startDate, days, scheduleId) {
    scheduleId = scheduleId || '8-5 weekdays excluding holidays';

    var schedule = new GlideSchedule(scheduleId);
    var duration = new GlideDuration(days * 24 * 60 * 60 * 1000);  // Convert days to ms

    var resultDate = new GlideDateTime(startDate);
    resultDate = schedule.add(resultDate, duration);

    return resultDate;
  },

  /**
   * Calculate business days between two dates
   * @param {GlideDateTime} startDate
   * @param {GlideDateTime} endDate
   * @param {string} scheduleId
   * @returns {number} Number of business days
   */
  getBusinessDaysBetween: function(startDate, endDate, scheduleId) {
    scheduleId = scheduleId || '8-5 weekdays excluding holidays';

    var schedule = new GlideSchedule(scheduleId);
    var duration = schedule.duration(startDate, endDate);

    // Convert duration to days (assuming 8-hour workday)
    var seconds = duration.getNumericValue();
    var businessDays = seconds / (8 * 60 * 60);

    return Math.round(businessDays * 10) / 10;  // Round to 1 decimal
  },

  /**
   * Get calendar days between two dates
   * @param {GlideDateTime} startDate
   * @param {GlideDateTime} endDate
   * @returns {number} Number of calendar days
   */
  getCalendarDaysBetween: function(startDate, endDate) {
    var start = new GlideDateTime(startDate);
    var end = new GlideDateTime(endDate);

    var diff = GlideDateTime.subtract(start, end);
    var days = diff.getNumericValue() / (1000 * 60 * 60 * 24);

    return Math.abs(Math.round(days));
  },

  /**
   * Check if a date is a weekend
   * @param {GlideDateTime} date
   * @returns {boolean}
   */
  isWeekend: function(date) {
    var gdt = new GlideDateTime(date);
    var dayOfWeek = gdt.getDayOfWeek();
    return dayOfWeek === 1 || dayOfWeek === 7;  // Sunday = 1, Saturday = 7
  },

  /**
   * Check if a date is a holiday
   * @param {GlideDateTime} date
   * @param {string} scheduleId
   * @returns {boolean}
   */
  isHoliday: function(date, scheduleId) {
    scheduleId = scheduleId || '8-5 weekdays excluding holidays';

    var schedule = new GlideSchedule(scheduleId);
    return !schedule.isInSchedule(date);
  },

  /**
   * Get the next business day
   * @param {GlideDateTime} date - Starting date
   * @param {string} scheduleId
   * @returns {GlideDateTime} Next business day
   */
  getNextBusinessDay: function(date, scheduleId) {
    scheduleId = scheduleId || '8-5 weekdays excluding holidays';

    var schedule = new GlideSchedule(scheduleId);
    var nextDay = new GlideDateTime(date);
    nextDay.addDaysLocalTime(1);

    // Keep adding days until we find a business day
    var maxAttempts = 10;  // Prevent infinite loop
    var attempts = 0;

    while (!schedule.isInSchedule(nextDay) && attempts < maxAttempts) {
      nextDay.addDaysLocalTime(1);
      attempts++;
    }

    return nextDay;
  },

  /**
   * Format date for display
   * @param {GlideDateTime} date
   * @param {string} format - 'short', 'long', 'iso', 'custom'
   * @returns {string} Formatted date string
   */
  formatDate: function(date, format) {
    var gdt = new GlideDateTime(date);
    format = format || 'short';

    switch(format) {
      case 'short':
        return gdt.getDisplayValue();  // MM/DD/YYYY HH:mm:ss

      case 'long':
        return gdt.getDisplayValueWithoutTZ();  // Full format

      case 'iso':
        return gdt.getValue();  // YYYY-MM-DD HH:mm:ss

      case 'date-only':
        return gdt.getDate().getDisplayValue();  // MM/DD/YYYY

      case 'time-only':
        return gdt.getTime().getDisplayValue();  // HH:mm:ss

      case 'custom':
        // Custom format: "January 15, 2024 at 2:30 PM"
        var monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
                         'July', 'August', 'September', 'October', 'November', 'December'];

        var month = monthNames[gdt.getMonth() - 1];
        var day = gdt.getDayOfMonth();
        var year = gdt.getYear();
        var hour = gdt.getHour();
        var minute = gdt.getMinute();
        var ampm = hour >= 12 ? 'PM' : 'AM';

        hour = hour % 12;
        hour = hour ? hour : 12;  // 0 should be 12
        minute = minute < 10 ? '0' + minute : minute;

        return month + ' ' + day + ', ' + year + ' at ' + hour + ':' + minute + ' ' + ampm;

      default:
        return gdt.getDisplayValue();
    }
  },

  /**
   * Get age in years, months, days from a date
   * @param {GlideDateTime} date - Birth date or start date
   * @returns {object} {years: number, months: number, days: number}
   */
  getAge: function(date) {
    var start = new GlideDateTime(date);
    var now = new GlideDateTime();

    var years = now.getYear() - start.getYear();
    var months = now.getMonth() - start.getMonth();
    var days = now.getDayOfMonth() - start.getDayOfMonth();

    // Adjust for negative days
    if (days < 0) {
      months--;
      // Get days in previous month
      var prevMonth = new GlideDateTime(now);
      prevMonth.addMonthsLocalTime(-1);
      var daysInPrevMonth = prevMonth.getDaysInMonth();
      days += daysInPrevMonth;
    }

    // Adjust for negative months
    if (months < 0) {
      years--;
      months += 12;
    }

    return {
      years: years,
      months: months,
      days: days,
      totalDays: this.getCalendarDaysBetween(start, now)
    };
  },

  /**
   * Check if date is within a date range
   * @param {GlideDateTime} checkDate
   * @param {GlideDateTime} startDate
   * @param {GlideDateTime} endDate
   * @returns {boolean}
   */
  isDateInRange: function(checkDate, startDate, endDate) {
    var check = new GlideDateTime(checkDate);
    var start = new GlideDateTime(startDate);
    var end = new GlideDateTime(endDate);

    return check.after(start) && check.before(end);
  },

  type: 'DateCalculator'
};

How to use it

1. Create a new Script Include named 'DateCalculator' 2. Leave 'Client callable' unchecked 3. Copy the code above 4. Use in Business Rules or Background Scripts: var calc = new DateCalculator(); var dueDate = calc.addBusinessDays(new GlideDateTime(), 5); var daysBetween = calc.getBusinessDaysBetween(start, end); var formatted = calc.formatDate(new GlideDateTime(), 'custom');

Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.