Skip to content

Instantly share code, notes, and snippets.

@ibernabel
Created February 19, 2024 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibernabel/0912cefe432a9f73fdcfa8962823cc4e to your computer and use it in GitHub Desktop.
Save ibernabel/0912cefe432a9f73fdcfa8962823cc4e to your computer and use it in GitHub Desktop.
Diff between two dates using vanilla JavaScript
// Fechas proporcionadas como cadenas
//const fechaInicioStr = "2017-08-01";
const fechaInicioStr = "2023-02-18";
const fechaFinalStr = "2024-02-17";
// Parsear las fechas
const fechaInicio = new Date(fechaInicioStr);
const fechaFinal = new Date(fechaFinalStr);
// Calcular la diferencia en milisegundos
const diffEnMilisegundos = fechaFinal - fechaInicio;
//console.log(diffEnMilisegundos)
// Convertir la diferencia a meses
const milisegundosPorDia = (1000 * 60 * 60 * 24)
const milisegundosPorMes = 1000 * 60 * 60 * 24 * 30;
const dias = diffEnMilisegundos / milisegundosPorDia;
const meses = Math.floor(diffEnMilisegundos / milisegundosPorMes);
const annos = Math.floor((diffEnMilisegundos / milisegundosPorMes) / 12);
console.log(dias)
console.log(meses)
console.log(annos)
//console.log(`La diferencia es de aproximadamente ${annos} annos.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment