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'], () => {
           const today = luxon.DateTime.now();

           // Add days to date
           const 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'], () => {
        const today = luxon.DateTime.now();

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

        // Subtract business days from date
        const 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'], () => {
           const locale = luxon.DateTime.local();

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

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

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

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

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

           const today = luxon.DateTime.now();
           // Add business days to date
           const 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() {
                const purchaseDate = fd.field('PurchaseDate').value;
                const deliveryDate = fd.field('DeliveryDate').value;

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

                     // Calculate the difference between two dates
                     const 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() {
                const locale = luxon.DateTime.local();
                // Define a workweek from 1 (Monday) to 4 (Thursday)
                const workWeek = [1, 2, 3, 4];

                locale.setupBusiness({
                     businessDays: workWeek
                });

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

                if (purchaseDate && deliveryDate) {
                     const startDate = luxon.DateTime.fromISO(purchaseDate.toISOString());
                     const 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() {
                const locale = luxon.DateTime.local();
                // Define a workweek from 1 (Monday) to 4 (Thursday)
                // Get schedule from the site's Regional Settings
                const workDays = _spPageContextInfo.webTimeZoneData.WorkHours.WorkDays;
                const workingDays = [];
                for (let d = 0; d < 7; d++) {
                     if (1 << (6 - d) & workDays) {
                           workingDays.push(d + 1);
                     }
                }

                locale.setupBusiness({
                     businessDays: workingDays
                });

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

                if (purchaseDate && deliveryDate) {
                     const startDate = luxon.DateTime.fromISO(purchaseDate.toISOString());
                     const 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();
     });

});