Search code examples
antd

How to open Antd Datepicker to a specific valid year?


I have a date picker on my form and what I need is to disable the years/months if the user is not 17 years old. So if the year is 2023 the allowable years should be 2006 below.

In my code, I can do that but I need to pass a specific day. In my case, I am passing the first day so that when the user clicks my date picker it will open to the year 2006.

How can I open it to the year 2006 but it should not have any value as selected by default?

Here's my code:

<Form.Item
    label="Birthdate"
    name="birthdate"
    initialValue={dayjs(allowedDates, 'MM/DD/YYYY').startOf('month')}
>
    <DatePicker
        allowClear={false}
        placeholder=""
        onChange={(date, dateString) => formik.setFieldValue('birthdate', dateString)}
        value={formik.values.birthdate ? moment(formik.values.birthdate, 'MM/DD/YYYY') : null}
        size="large"
        style={{ width: '100%' }}
        format="MM/DD/YYYY"
        disabledDate={(current) =>
            current && current > moment().subtract(17, 'years')
        }
    />
</Form.Item>

I hope you can help me. I checked the documentation but I didn't find any solution. https://ant.design/components/date-picker


Solution

  • You can use defaultPickerValue, this is mentioned in the docs.

    defaultPickerValue={dayjs(dayjs().subtract(17, "years"))}