I want to check if the given date is higher than 10 years ago from today (so the person would have less than 10 years). I have searched many info with no possitive result.
EDIT: When I alert “objetoFechaNacimiento”, if the user entered “22/1/2015”, it alerts “Sat Oct 01 2016 00:00:00 GMT+0200”. This must be the problem…
This is what I got:
JavaScript
x
11
11
1
var nacimiento = document.getElementById("fechaNacimiento").value;
2
var objetoFechaActual = new Date();
3
var objetoFechaNacimiento = new Date(nacimiento);
4
var fechaMinima = objetoFechaActual.setYear(objetoFechaActual.getFullYear() - 10);
5
var objetoFechaMinima = new Date(fechaMinima);
6
7
if ( objetoFechaNacimiento.getTime() >= objetoFechaMinima.getTime() ) {
8
alert("You can not be less than 10 years old.");
9
return false;
10
}
11
Advertisement
Answer
Just reformat the date to a valid format
Also when you create a minima date you can use setFullYear on that date instead of saving the result of a setDate
JavaScript
1
14
14
1
const nacimiento = document.getElementById("fechaNacimiento").value;
2
const [dd, mm, yyyy] = nacimiento.split("/");
3
var objetoFechaNacimiento = new Date(yyyy, mm - 1, dd, 15, 0, 0, 0); // let's normalise at 15:00 to not run into midnight and daylight-saving
4
5
const objetoFechaMinima = new Date();
6
objetoFechaMinima.setFullYear(objetoFechaMinima.getFullYear() - 10);
7
objetoFechaMinima.setHours(15, 0, 0, 0); // also normalise;
8
9
console.log(objetoFechaNacimiento,objetoFechaMinima)
10
11
12
if (objetoFechaNacimiento.getTime() >= objetoFechaMinima.getTime()) {
13
console.log("You can not be less than 10 years old.");
14
}
JavaScript
1
1
1
<input type="text" id="fechaNacimiento" value="24/12/2020" />