How to work with Date and Time fields in SharePoint forms with JavaScript

In this article, you will find the most common examples of working with the Date & Time field.

Using the Luxon library and its plugin, you can easily calculate the duration between dates, add or subtract time from the date, calculate the number of business days between dates, etc.

Add or subtract from a date

With the help of the Luxon library, you can add and subtract date and time values to calculate future and past dates.

In Luxon, you can specify a time unit that you want to use in the calculation. Find more info on using the time units here.

Assume we want to populate a due date field as today plus 3 days on loading a new form. This can be done with Luxon:

// load external library
requirejs.config({
    paths: {
        luxon: 'https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min'
    }
});

fd.spRendered(() => {
    require(['luxon'], () => {
        let today = luxon.DateTime.now();

        // add days to date
        let newDate = today.plus({
            days: 3
        });

        // populate the field with the calculated date on form load
        fd.field('DueDate').value = newDate.toJSDate();
    });
});

Using a similar approach, you can calculate dates by adding or subtracting time in any units—days, weeks, etc. You can find more examples in the documentation.

Add or subtract business days from a date

With the help of the Luxon Business Days plugin, you can add and subtract business days from a date.

// load external library
requirejs.config({
    paths: {
        luxon: 'https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min',
        'luxon-business-days': 'https://cdn.jsdelivr.net/npm/luxon-business-days@3.0.1/dist/index'
    }
});

fd.spRendered(() => {
    require(['luxon', 'luxon-business-days'], () => {
        let today = luxon.DateTime.now();

        // add business days to date
        let futureDate = today.plusBusiness({
            days: 7
        });

        // subtract business days from date
        let pastDate = today.minusBusiness({
            days: 3
        });

        // populate the fields with the calculated dates on form load
        fd.field('FutureDate').value = futureDate.toJSDate();
        fd.field('PastDate').value = pastDate.toJSDate();
    });
});

You can customize the working week and also define custom dates for holidays to exclude them from being counted as business days, for example, national holidays. Learn more here.

// load external library
requirejs.config({
    paths: {
        luxon: 'https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min',
        'luxon-business-days': 'https://cdn.jsdelivr.net/npm/luxon-business-days@3.0.1/dist/index'
    }
});

fd.spRendered(() => {
    require(['luxon', 'luxon-business-days'], () => {
        let locale = luxon.DateTime.local();

        // define a workweek from 1 (Monday) to 7 (Sunday)
        let workWeek = [1, 2, 3, 7];

        // define custom holidays
        let customHolidays = function(inst) {
            let firstSpringDay = luxon.DateTime.fromObject({
                month: 3,
                day: 1
            });
            let lastSummerDay = luxon.DateTime.fromObject({
                month: 8,
                day: 31
            });

            // match the following two days regardless of year
            return +inst === +firstSpringDay || +inst === +lastSummerDay;
        };

        let holidays = [
            locale.availableHolidayMatchers.isNewYearsDay,
            locale.availableHolidayMatchers.isChristmasDay,
            customHolidays
        ];

        // set up business days and holidays
        locale.setupBusiness({
            businessDays: workWeek,
            holidayMatchers: holidays
        });

        let today = luxon.DateTime.now();
        // add business days to date
        let futureDate = today.plusBusiness({
            days: 7
        });

        // populate the field with the calculated date on form load
        fd.field('FutureDate').value = new Date(futureDate);
    });
});

Calculate the number of days between two dates

You can also calculate the difference between two dates in years, months, days, etc. using the diff method.

Suppose you need to know how many days have passed since the purchase until the delivery date.

// load external library
requirejs.config({
    paths: {
        luxon: 'https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min'
    }
});

fd.spRendered(() => {
    require(['luxon'], () => {
        function updateDaysToDelivery() {
            let purchaseDate = fd.field('PurchaseDate').value;
            let deliveryDate = fd.field('DeliveryDate').value;

            if (purchaseDate && deliveryDate) {
                let startDate = luxon.DateTime.fromISO(purchaseDate.toISOString());
                let endDate = luxon.DateTime.fromISO(deliveryDate.toISOString());

                // calculate the difference between two dates
                let dateDiff = endDate.diff(startDate, 'days').as('days');
                // populate the field with the calculated value
                fd.field('DeliveryPeriod').value = dateDiff;
            }
        }

        // call the function when a user changes a field value
        fd.field('PurchaseDate').$on('change', updateDaysToDelivery);
        fd.field('DeliveryDate').$on('change', updateDaysToDelivery);

        // call the function on form load
        updateDaysToDelivery();
    });
});

Calculate the number of business days between dates

Also, you can find the difference between two dates, excluding weekends and holidays using the Luxon Business Days plugin. In the code example below, we defined a four-day workweek, Monday through Thursday.

// load external library
requirejs.config({
    paths: {
        luxon: 'https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min',
        'luxon-business-days': 'https://cdn.jsdelivr.net/npm/luxon-business-days@3.0.1/dist/index'
    }
});

fd.spRendered(() => {
    require(['luxon', 'luxon-business-days'], () => {
        function updateDaysToDelivery() {
            let locale = luxon.DateTime.local();
            // define a workweek from 1 (Monday) to 4 (Thursday)
            let workWeek = [1, 2, 3, 4];

            locale.setupBusiness({
                businessDays: workWeek
            });

            let purchaseDate = fd.field('PurchaseDate').value;
            let deliveryDate = fd.field('DeliveryDate').value;

            if (purchaseDate && deliveryDate) {
                let startDate = luxon.DateTime.fromISO(purchaseDate.toISOString());
                let endDate = luxon.DateTime.fromISO(deliveryDate.toISOString());

                let dateDiff = 0;
                let currentDate = startDate;

                while (currentDate < endDate) {
                    currentDate = currentDate.plusBusiness({
                        days: 1
                    });
                    if (currentDate <= endDate) {
                        dateDiff++;
                    }
                }

                // populate the field with the calculated value
                fd.field('DeliveryPeriod').value = dateDiff;
            }
        }

        // call the function when a user changes a field value
        fd.field('PurchaseDate').$on('change', updateDaysToDelivery);
        fd.field('DeliveryDate').$on('change', updateDaysToDelivery);

        // call the function on form load
        updateDaysToDelivery();
    });
});

You can add and subtract the given number of days skipping business days using the same plugin. Please find more details here.

Calculate the number of business days between dates based on Regional Settings

You can define a workweek in the site’s regional settings. Go to Site Settings → Site Administration → Regional Settings.

Regional settings

Based on those settings, you can calculate business days between two dates using this code:

// load external library
requirejs.config({
    paths: {
        luxon: 'https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min',
        'luxon-business-days': 'https://cdn.jsdelivr.net/npm/luxon-business-days@3.0.1/dist/index'
    }
});

fd.spRendered(() => {
    require(['luxon', 'luxon-business-days'], () => {
        function updateDaysToDelivery() {
            let locale = luxon.DateTime.local();
            // define a workweek from 1 (Monday) to 4 (Thursday)
            // get schedule from the site's Regional Settings
            let workDays = _spPageContextInfo.webTimeZoneData.WorkHours.WorkDays;
            let workingDays = [];
            for (let d = 0; d < 7; d++) {
                if (1 << (6 - d) & workDays) {
                    workingDays.push(d + 1);
                }
            }

            locale.setupBusiness({
                businessDays: workingDays
            });

            let purchaseDate = fd.field('PurchaseDate').value;
            let deliveryDate = fd.field('DeliveryDate').value;

            if (purchaseDate && deliveryDate) {
                let startDate = luxon.DateTime.fromISO(purchaseDate.toISOString());
                let endDate = luxon.DateTime.fromISO(deliveryDate.toISOString());

                let dateDiff = 0;
                let currentDate = startDate;

                while (currentDate < endDate) {
                    currentDate = currentDate.plusBusiness({
                        days: 1
                    });
                    if (currentDate <= endDate) {
                        dateDiff++;
                    }
                }

                // populate the field with the calculated value
                fd.field('DeliveryPeriod').value = dateDiff;
            }
        }

        // call the function when a user changes a field value
        fd.field('PurchaseDate').$on('change', updateDaysToDelivery);
        fd.field('DeliveryDate').$on('change', updateDaysToDelivery);

        // call the function on form load
        updateDaysToDelivery();
    });
});