Created
February 19, 2024 21:28
-
-
Save ibernabel/0912cefe432a9f73fdcfa8962823cc4e to your computer and use it in GitHub Desktop.
Diff between two dates using vanilla JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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