我如何从出生日期计算年龄反应js



我有我的注册表单。我正在尝试从用户的出生日期计算他们的年龄,我发现了很多版本,但没有一个可以根据我的项目进行调整,你能帮我提出想法吗,谢谢。我把我的登记表附在下面。我想实现的是,当用户输入他的出生日期和输入日期时,它不会在html中显示年龄,而是保存它并能够在我的数据库中使用它

import { useHistory } from "react-router-dom";
import { addUser, cleanUsers} from "../actions/index.js";
import { React, useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Button, Col, Container, Form, Row } from "react-bootstrap";
import { useDispatch , useSelector } from "react-redux";
import swal from "sweetalert";
import imgIcon from "./img/programmer.png";
import style from "../styles/RegisterUser.module.css";
import NavBarRegisters from "./NavBarRegisters.jsx";
function RegisterUser() {
const dispatch = useDispatch();
const history = useHistory();
const [errors, setErrors] = useState({});
const [input, setInput] = useState({
email: "",
password: "",
confirmPassword: "",
name: "",
lastname: "",
birthDate: "",
});
function handleChange(e) {
setInput({
...input,
[e.target.name]: e.target.value,
});
setErrors(
validateUsers({
...input,
[e.target.name]: e.target.name,
})
);
}
function handleSubmit(e) {
e.preventDefault();
if (input.password !== input.confirmPassword) {
swal(
"Las contraseñas no coinciden",
"Por favor vuelva a ingresar su contraseña",
"error"
);
return;
}
if (
input.email !== "" &&
input.password !== "" &&
input.password === input.confirmPassword &&
input.password.length >= 8 &&
input.password.length <= 16 &&
input.confirmPassword.length >= 8 &&
input.confirmPassword.length <= 16 &&
input.name !== "" &&
input.lastname !== "" &&
input.birthDate !== ""
) {
dispatch(addUser(input));

} else {
swal(
"Faltan datos por llenar",
"Por favor ingrese todos los datos",
"error"
);
}
}
const user = useSelector((state) => state.user);
const [didMount, setDidMount] = useState(true);
useEffect(() => {
if (didMount) {
setDidMount(false);
return; 
} else {
if ( user === "Usuario creado") {
swal("Buen trabajo!", "El usuario fue creado con exito!", "success");
setInput({
email: "",
password: "",
name: "",
lastname: "",
birthDate: "",
});
history.push("/persona");
} else if ( user === "error:Validation error") {
swal("Ya existe un usuario con el email");
dispatch(cleanUsers());
}
}
}, [user]);

return (
<div className={style.divContainer}>
<NavBarRegisters />
<div className={style.divContainerForms}>
<Container>
<h1 className="shadow-sm text-success mt-5 p-3 text-center rounded">
Registrar Usuario
</h1>
<Row>
<Col
lg={8}
md={6}
sm={12}
className="text-center p-5 m-auto shadow-sm rounded-lg"
>
<img className="iconImg" src={imgIcon} alt="icon" />
<Form onSubmit={(e) => handleSubmit(e)} className={style.forms}>
<Form.Group className="mb-3">
<Form.Label>Email address</Form.Label>
<Form.Control
placeholder="Enter email"

</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Fecha nacimiento</Form.Label>
<Form.Control
type="date"
placeholder="Fecha de nacimiento"
onChange={(e) => handleChange(e)}
value={input.birthDate}
name="birthDate"
id="birthDate"
required
/>
</Form.Group>
<Button
variant="primary"
className="mt-3 mb-5 w-100 mt-3"
type="submit"
>
REGISTRARME
</Button>
</Form>
</Col>
</Row>
<h6 className="mt-5 p-5 text-center text-secondary ">
© 2022 Bring it. All Rights Reserved | Design by Grupo 8 Soy Henry
</h6>
</Container>
</div>
</div>
);
}
export default RegisterUser;

您可以创建一个计算它的函数,或者更容易地使用像Moment.jsDatefns这样的库计算天数的功能-psuedo代码/算法可能来自

https://stackoverflow.com/a/7091965/18821127

function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}

相关内容

  • 没有找到相关文章

最新更新