Skip to content
Advertisement

Compare date with todays date 10 years ago

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:

  var nacimiento = document.getElementById("fechaNacimiento").value;
  var objetoFechaActual = new Date();
  var objetoFechaNacimiento = new Date(nacimiento);
  var fechaMinima = objetoFechaActual.setYear(objetoFechaActual.getFullYear() - 10);
  var objetoFechaMinima = new Date(fechaMinima);

  if ( objetoFechaNacimiento.getTime() >= objetoFechaMinima.getTime() ) {
        alert("You can not be less than 10 years old.");
        return false;
  }

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

const nacimiento = document.getElementById("fechaNacimiento").value;
const [dd, mm, yyyy] = nacimiento.split("/");
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

const objetoFechaMinima = new Date();
objetoFechaMinima.setFullYear(objetoFechaMinima.getFullYear() - 10);
objetoFechaMinima.setHours(15, 0, 0, 0); // also normalise;

console.log(objetoFechaNacimiento,objetoFechaMinima)


if (objetoFechaNacimiento.getTime() >= objetoFechaMinima.getTime()) {
  console.log("You can not be less than 10 years old.");
}
<input type="text" id="fechaNacimiento" value="24/12/2020" />
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement