如何按年龄计算出生日期?

时间:2021-06-16 15:59:29

标签: react-hooks formik

在 formik 中有两个字段,一个是年龄,一个是出生日期,还有一个按钮,我想从 age 计算出生日期。如果我给出年龄并输入计算按钮。我想设置出生日期。已经写了一个函数,但它不起作用。你能帮我得到正确的答案吗?这是以下代码。

  const age = values.age;

  const getDisplayDate = (date) => {
    if (date === null || date === undefined || date === "") {
      return null;
    }

    let d = typeof date === "string" ? new Date(date) : date;

    const year = d.getFullYear() - age;
    let month = d.getMonth() + 1;
    let day = d.getDate();

    if (month < 10) {
      month = "0" + month;
    }

    if (day < 10) {
      day = "0" + day;
    }
    console.log(`day:${day}/month:${month}/year:${year}`);
    return `${year}-${month}-${day}`;
  };


Here is form :
        <div className="form-group col-md-4">
          <label htmlFor="age">Age</label>
          <Field
            type="text"
            className={`form-control form-control-sm ${getError(basicInformationError, 
basicInformationTouched, "age")
              ? "is-invalid"
              : ""
              }`}
            id="age"
            name="basicInformation.age"
            value={basic.age}
            placeholder="age"
          />
          <ErrorMessage
            name="basicInformation.age"
            component="div"
            className="invalid-feedback"
          />
        </div>

        <div className="form-group col-md-4">
          <div className="row">
            {/* <div className="col"> */}
            <label htmlFor="date">Date Of Birth</label>
            <Field
              type="date"
              className={`form-control form-control-sm ${getError(
                basicInformationError,
                basicInformationTouched,
                "dateOfBirth"
              )
                ? "is-invalid"
                : ""
                }`}
              id="date"
              name="basicInformation.dateOfBirth"
              value={getDisplayDate(basic.dateOfBirth) || ""}
              // onChange={(e) => setFieldValue(valu)}
              placeholder="date"
            />
            <ErrorMessage
              component="div"
              name="basicInformation.dateOfBirth"
              className="invalid-feedback"
            />
            {/* </div> */}

            <button
              type="button"
              className="btn btn-sm btn btn-info mt-2"
              onClick={getDisplayDate}
            >
              Calculate DOB
            </button>
          </div>
        </div>


Output:

[![enter image description here][1]][1]

                       


  [1]: https://i.stack.imgur.com/8xaPn.png

1 个答案:

答案 0 :(得分:0)

const handleAgeChange = (event) => {
  const {
    target: { value }
  } = event;

  handleChange(event);

  const date = new Date();

  date.setFullYear(date.getFullYear() - Number(value));

  setFieldValue("dateOfBirth", date.toLocaleDateString());
};

https://codesandbox.io/s/recursing-bogdan-miip7?file=/index.js

对你有帮助吗?