How to work with Date and Time fields in public web form 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:

const setDueDate = async () => {
    // Load external libraries
    await $.getScript('https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min.js');

    // Get today's date
    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();
}

fd.rendered(function() {
    // Call the function on form load
    setDueDate();
});

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.

const calculateBusinessDays = async () => {
    // Load external libraries
    await $.getScript('https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min.js');
    await $.getScript('https://cdn.jsdelivr.net/npm/luxon-business-days@3.0.1/dist/index.js');

    // Get today's date
    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();
}

fd.rendered(() => {
    // Call the function on form load
    calculateBusinessDays();
});

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.

const defineBusinessDays = () => {
    // Get locale settings
    const locale = luxon.DateTime.local();

    // Define a workweek
    // 1 is Monday and 7 is 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 addBusinessDays = async () => {
    // Load external libraries
    await $.getScript('https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min.js');
    await $.getScript('https://cdn.jsdelivr.net/npm/luxon-business-days@3.0.1/dist/index.js');

    // Define business days and holidays
    defineBusinessDays();

    // Get today's date
    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);
}

fd.rendered(() => {
    // Call function on form load
    addBusinessDays();
});

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.

const loadLuxon = async () => {
    // Load external library
    await $.getScript('https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min.js');
}

const 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;
    }
}

fd.rendered(() => {
    loadLuxon().then(() => {
        // Call the function when a user changes a field value
        fd.field('PurchaseDate').$on('change', updateDaysToDelivery);
        fd.field('DeliveryDate').$on('change', updateDaysToDelivery);

        // Call 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.

const loadLuxon = async () => {
    // Load external library
    await $.getScript('https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min.js');
    await $.getScript('https://cdn.jsdelivr.net/npm/luxon-business-days@3.0.1/dist/index.js');
}

const updateDaysToDelivery = () => {
    // Get locale settings
    const locale = luxon.DateTime.local();

    // Define a workweek
    // 1 is Monday and 7 is Sunday
    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;
    }
}

fd.rendered(() => {
    loadLuxon().then(() => {
        // Call the function when a user changes a field value
        fd.field('PurchaseDate').$on('change', updateDaysToDelivery);
        fd.field('DeliveryDate').$on('change', updateDaysToDelivery);

        // Call 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.