Jordan Rob
Jordan Rob

Reputation: 362

Change date format in antd <DatePicker />

I'm submitting a form to send data to my API that receives date in the format of YYYY-MM-DD but by default the DatePicker component keeps adding extra characters of time to the end of the date, for example when I enter a date for my date of birth field the value is stored in the format below

{
  "date_of_birth":"2003-02-03T13:32:49.543Z"
}

I would prefer it to be just

{
  "date_of_birth":"2003-02-03"
}

below is the code for the form and its submit function

const Demo = () => {
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();

  const showUserModal = () => {
    setVisible(true);
  };

  const hideUserModal = () => {
    setVisible(false);
  };

  const onFinish = values => {
    console.log(JSON.stringify(values))
    const userToken = localStorage.getItem(AUTH_TOKEN)
    IndividualService.setToken(userToken)

    IndividualService.postIndividual(values).then(resp => {
        console.log(resp)
        message.success('successfully added details for Individual plan')

    }).catch(error => {
        message.error('Error occured, plase try again', error.message)
      })
    
  };

  const customFormat = value => `custom format: ${value.format("YYYY-MM-DD")}`;

  return (
    <Card title='Enter Customer details for individual plan'>
      <Row justify='center'>
        <Col span={20}>
            <Form.Provider
                onFormFinish={(name, { values, forms }) => {
                if (name === 'userForm') {
                    const { basicForm } = forms;
                    const dependants = basicForm.getFieldValue('dependants') || [];
                    basicForm.setFieldsValue({
                        dependants: [...dependants],
                        ...values
                    });
                    setVisible(false);
                }
                }}
            >
                <Form {...layout} name="basicForm" onFinish={onFinish} size='small'>
                <Form.Item
                    name="first_name"
                    label="First Name"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="other_names"
                    label="Other Names"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="gender"
                    label="Gender"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Select>
                        <Option value="MALE">male</Option>
                        <Option value="FEMALE">female</Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    name="date_of_birth"
                    label="Date of Birth"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <DatePicker format={customFormat} />
                </Form.Item>
                <Form.Item
                    name="blood_group"
                    label="Blood Group"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="residential_address"
                    label="Residential address"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="workplace_address"
                    label="Workplace address"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="additional_telephone_no"
                    label="Additional phone no."
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="NIN"
                    label="NIN"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="next_of_kin_name"
                    label="Next of kin name"
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="next_of_kin_telephone"
                    label="next of kin phone."
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="next_of_kin_email"
                    label="next of kin email."
                    rules={[
                    {
                        required: true,
                    },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="dependants"
                    label="Dependants List"
                    shouldUpdate={(prevValues, curValues) => prevValues.dependants !== curValues.dependants}
                >
                    {({ getFieldValue }) => {
                    const dependants = getFieldValue('dependants') || [];
                    return dependants.length ? (
                        <ul>
                        {dependants.map((d, index) => (
                            <li key={index} className="user">
                            <Avatar icon={<UserOutlined />} />
                            <p>{d.first_name} - {d.relationship}</p>
                            </li>
                        ))}
                        </ul>
                    ) : (
                        <Typography.Text className="ant-form-text" type="secondary">
                        ( <SmileOutlined /> No dependant yet. )
                        </Typography.Text>
                    );
                    }}
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Button htmlType="submit" type="primary">
                    Submit
                    </Button>
                    <Button
                    htmlType="button"
                    style={{
                        marginLeft: 8,
                    }}
                    onClick={showUserModal}
                    >
                    Add User
                    </Button>
                </Form.Item>
                </Form>

                <ModalForm visible={visible} onCancel={hideUserModal} />
            </Form.Provider>
        </Col>
      </Row>
    </Card>
  );
};

Upvotes: 2

Views: 18432

Answers (3)

Kenneth Pole
Kenneth Pole

Reputation: 41

You can do this by adding a prop to format the date within the form.item ANTD updates the date package from moment to dayjs. Make sure you install the dayjs

   <Form.Item
      name="date_of_birth"
      label="Date of Birth"
      initialValue=""
      rules={[
        {
          required: true,
          message: "Date of Birth field required!",
        },
      ]}
      //add these two props
      getValueFromEvent={(e: any) => e?.format("YYYY-MM-DD")}
      getValueProps={(e: string) => ({
        value: e ? dayjs(e) : "",
      })}
    >
      <DatePicker
        onChange={handleChangeAge}
        style={{ width: "100%" }}
        format="YYYY-MM-DD"
        allowClear
        //disable future dates
        disabledDate={(current) => {
          let customDate = dayjs().format("YYYY-MM-DD");
          return current && current > dayjs(customDate, "YYYY-MM-DD");
        }}
      />
    </Form.Item>

Upvotes: 4

Emamuzo
Emamuzo

Reputation: 11

In my case, the elements in the form are dynamically generated. So I had to set the format twice:

  1. When the DatePicker element is first created:

<Form onFinish={onFinish}><DatePicker format="MM/DD/YYYY"/></Form>

  1. When the form is submitted, I changed the date fields dynamically like this: const onFinish = values => { for(const[key, value] of Object.entries(values)){ if(typeof value.toDate=='function') values[key] = value.format('MM/DD/YYYY');}}

Upvotes: 0

NeERAJ TK
NeERAJ TK

Reputation: 2695

You can add the prop format to get the input in custom format, as

<DatePicker
  format="YYYY-MM-DD"
/>

This will display the date in the format YYYY-MM-DD in the date picker. To convert this to the required format you may need to format it in the onFinish , as:

  const onFinish = values => {
    console.log(JSON.stringify(values))
    const userToken = localStorage.getItem(AUTH_TOKEN)
    IndividualService.setToken(userToken)
    values["date_of_birth"] = moment(values.date_of_birth).format("YYYY-MM-DD")
    IndividualService.postIndividual(values).then(resp => {
        console.log(resp)
        message.success('successfully added details for Individual plan')

    }).catch(error => {
        message.error('Error occured, plase try again', error.message)
      })
    
  };

Upvotes: 3

Related Questions