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

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

Using the Moment.js library and its plugins, you can easily calculate duration between dates, add or subtract time from the date, calculate a number of business days/hours between dates, etc.

Add to or Subtract from a Date

With the help of the Moment.js library, you can add and subtract date and time values to calculate future and past dates. In Moment.js 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 Moment.js:

requirejs.config({
    paths: {
        moment: "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min"
    }
});

fd.spRendered(function() {
    require(['moment'], function(moment) {
        var today = moment(new Date());
        var newDate = today.add(3, 'days');
        fd.field('DueDate').value = moment(newDate).toDate();
    })
});

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.

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.

requirejs.config({
    paths: {
        moment: "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min"
    }
});

fd.spRendered(function() {

    require(['moment'], function(moment) {

        function diffDays() {
            var purchase = moment(fd.field('PurchaseDate').value);
            var delivery = moment(fd.field('DeliveryDate').value);
            if (purchase.isValid() && delivery.isValid()) {
                var dateDiff = delivery.diff(purchase, 'days', false);
                fd.field('DeliveryPeriod').value = dateDiff;
            }
        }

        // Calling function when the user changes the date
        fd.field('PurchaseDate').$on('change', diffDays);
        fd.field('DeliveryDate').$on('change', diffDays);

        // Calling function on form loading
        diffDays ();
    });
});

Calculate the number of business days between dates

Also, you can find the difference between two dates, excluding weekends and holidays. For this, we will use moment-business-days.js, which is a Moment.js plugin that allows working with business days only.

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

In the code example below, we defined a four-day workweek, Monday through Thursday, and specified the holidays.

requirejs.config({
    paths: {
        moment: "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min",
        'moment-business-days': "https://cdn.jsdelivr.net/npm/moment-business-days@1.1.3/index.min"
    }
});

fd.spRendered(function() {

    require(['moment'], function(moment) {
        require(['moment-business-days'], function() {

             function calcDiff() {
                var diff = 0;
                var startDate = moment(fd.field('StartDate').value);
                var endDate = moment(fd.field('EndDate').value);
                if (startDate.isValid() && endDate.isValid()) {
                    diff = endDate.businessDiff(startDate);
                }
                console.log(diff);
            }

            function defineWorkDays () {
                //Define holidays that you do not want to be considered working days
                var july4th = '07-04-2020';
                var laborDay = '09-07-2020';
                moment.updateLocale('us', {
                    // Defines days from 1 (Monday) to 6 (Saturday) as business days. Note that Sunday is day 0.
                    // When omitting this configuration parameter, business days are based on locale default
                    workingWeekdays: [1, 2, 3, 4],
                    holidays: [july4th, laborDay],
                    holidayFormat: 'MM-DD-YYYY'
                });
            }

            // Defining Work Days and Holidays on form loading
            defineWorkDays ();

            // Calling function when the user changes the date
            fd.field('StartDate').$on('change', calcDiff);
            fd.field('EndDate').$on('change', calcDiff);

            // Calling function on form loading
            calcDiff();
        });
    });
});

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:

requirejs.config({
    paths: {
        moment: "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min",
        'moment-business-days': "https://cdn.jsdelivr.net/npm/moment-business-days@1.1.3/index.min"
    }
});

fd.spRendered(function() {

    require(['moment'], function(moment) {
        require(['moment-business-days'], function() {

            function calcDiff() {
                var diff = 0;
                var startDate = moment(fd.field('StartDate').value);
                var endDate = moment(fd.field('EndDate').value);
                if (startDate.isValid() && endDate.isValid()) {
                    diff = endDate.businessDiff(startDate);
                }
                console.log(diff);
            }

            pnp.sp.web.regionalSettings.get().then(function(rs) {
                var workingWeekdays = [];
                for (var d = 0; d < 7; d++) {
                    if (Math.pow(2, 6-d) & rs.WorkDays) {
                        workingWeekdays.push(d);
                    }
                }

            moment.updateLocale(_spPageContextInfo.currentUICultureName, {
                workingWeekdays: workingWeekdays
            });

            // Calling function when the user changes the date
            fd.field('StartDate').$on('change', calcDiff);
            fd.field('EndDate').$on('change', calcDiff);

            // Calling function on form loading
            calcDiff();
            });
        });
    });
});

Calculate the number of business hours between dates

Using the moment-business-time.js plugin, we can calculate the working hours between two dates.

By default, the working hours are 09:00-17:00, Monday through Friday. But you can specify custom working hours as shown in this code example:

requirejs.config({
    paths: {
        moment: "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min",
        'moment-business-time': "https://forms.plumsail.com/libs/moment-business-time"
    }
});

fd.spRendered(function() {

    require(['moment'], function(moment) {
        require(['moment-business-time'], function() {

            function calcDiff() {
                var diff = 0;
                var startDate = moment(fd.field('StartDate').value);
                var endDate = moment(fd.field('EndDate').value);
                if (startDate.isValid() && endDate.isValid()) {
                    diff = endDate.workingDiff(startDate, 'hours');
                }

                console.log(diff);
            }

            //Function that defines working hours
            function defineWorkHours () {

                moment.locale('en', {
                    workinghours: {

                        0: null,
                        1: ['09:30:00', '16:00:00'],
                        2: ['09:30:00', '17:00:00'],
                        3: ['09:30:00', '13:00:00'],
                        4: ['09:30:00', '17:00:00'],
                        5: ['09:30:00', '17:00:00'],
                        6: null
                    }
                });
            }

            defineWorkHours ();

            // Calling function when the user changes the date
            fd.field('StartDate').$on('change', calcDiff);
            fd.field('EndDate').$on('change', calcDiff);

            // Calling function on form loading
            calcDiff();
        });
    });
});

You can add and subtract working hours using the same plugin. Please find more details here.

Examples

Please see this article to learn how to create SharePoint form for booking a meeting room.