javascriptreactjsantdant-design-pro

How to automatically calculate and display next due date based on user selected options and input


I created a form using antd proform with 4 fields. The first field is an input number named interval, the second is a select field with 2 options: "day(s)" and "month(s)", the third and fourth are datepicker fields. For example, if the user enters 30 as an interval, selects "days", and selects 2023-08-10 as the last due date, the next due date should be calculated automatically and displayed (2023-09-09) in the fourth field. How can I do this?

Here is my code:

<ProForm.Group>
    <ProFormDigit 
        onChange={(value) => setIntervalDays(value)} 
        name="interval" 
        label="Interval" />
    <ProFormSelect
        onChange={(value) => setKindOfDate(value)}
        name="kindOfDate"
        label=""
        options={[
            {
              value: "1",
              label: "Day(s)",
            },
            {
              value: "2",
              label: "Month(s)",
            },
        ]}
    />
</ProForm.Group>
<ProForm.Group>
    <ProFormDatePicker 
        onChange={(value) => setLastDueDate(value)} 
        name="lastDueDate" 
        label="Last Due Date" 
    />
    <ProFormDatePicker 
        onChange={(value) => setNextDueDate(value)} 
        name="nextDueDate" 
        label="Next Due Date" 
    />
</ProForm.Group>
             

Solution

  • First of all, the Date object of javascript isn't the best (in my opinion), you have better libraries that can do the work in such a great way.

    Let's say the form part is done (get user input values).

    You can do it with Date object like this :

    // Convert the lastDueDate to Date object
    const date = new Date(lastDueDate)
    
    // create your nextDueDate depending on which interval and unit you chose
    if (unit === 'days') {
        date.setDate(date.getDate() + intervalValue)
    } else if (unit === 'months') {
        date.setMonth(date.getMonth() + intervalValue)
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    console.log(`Next due date: ${year}-${month}-${day}`)
    

    Or, you can simply add "moment" library to your project and use this function :

    // import moment
    import moment from 'moment'
    
    const calculateDueDate = (interval, unit, dueDate) => {
       const nextDueDate = moment(dueDate).add(interval, unit);
       return nextDueDate.format('YYYY-MM-DD');
    }
    

    Hope it helps, i can help you more if you need to fetch values and call the function correctly.