修改 antd 中的日期格式 <DatePicker />

Change date format in antd <DatePicker />

我正在提交一个表单以将数据发送到我的 API,该表单接收格式为 YYYY-MM-DD 的日期,但默认情况下 DatePicker 组件会在日期末尾添加额外的时间字符日期,例如,当我在出生日期字段中输入日期时,该值以以下格式存储

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

我希望它只是

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

下面是表单及其提交函数的代码

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

您可以添加属性 format 以获取自定义格式的输入,如

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

这将在日期选择器中以 YYYY-MM-DD 格式显示日期。 要将其转换为所需格式,您可能需要在 onFinish 中对其进行格式化,如:

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