Calculating Date Differences in SuiteScript

This article provides a reusable SuiteScript 2.x utility function to calculate the number of days between two dates. The function ensures proper date parsing using NetSuite’s N/format module and includes error handling, input validation, and logging.

Usage

  • Accepts two date strings in MM/DD/YYYY or NetSuite’s UI format.
  • Converts them into Date objects.
  • Computes the difference in days.
  • Returns the rounded number of days or null if an error occurs.

/**
 * @NApiVersion 2.x
 * @NModuleScope Public
 * @Description Utility function to calculate the difference between two dates in days.
 */


define(['N/format'], function(format) {


    /**
     * Calculate the difference between two dates in days.
     * @param {string} date1Str - First date in string format (MM/DD/YYYY or NetSuite UI format).
     * @param {string} date2Str - Second date in string format.
     * @returns {number|null} - The difference in days (rounded), or null if an error occurs.
     */
    function getDateDifference(date1Str, date2Str) {
        try {
            // Validate inputs
            if (!date1Str || !date2Str) {
                return null;
            }

            // Convert date strings to Date objects
            var date1 = format.parse({
                value: date1Str,
                type: format.Type.DATE
            });
            var date2 = format.parse({
                value: date2Str,
                type: format.Type.DATE
            });

            // Calculate time difference in milliseconds
            var timeDiff = date1.getTime() - date2.getTime();
            
            // Convert milliseconds to days (1 day = 86400000 ms)
            return Math.round(timeDiff / (1000 * 3600 * 24));

        } catch (e) {
            return null;
        }
    }

    return {
        getDateDifference: getDateDifference
    };

});

Leave a comment

Your email address will not be published. Required fields are marked *