Obtain Difference Between Two Dates In Years, Months, Days In Javascript
well, I found a lot of questions like that here trying to obtain the difference between 2 dates in years, month and days... But no answers that complete my requirement. So i wrote
Solution 1:
You can use moment.js to simplify this:
functiondifference(d1, d2) {
var m = moment(d1);
var years = m.diff(d2, 'years');
m.add(-years, 'years');
var months = m.diff(d2, 'months');
m.add(-months, 'months');
var days = m.diff(d2, 'days');
return {years: years, months: months, days: days};
}
For example,
> difference(Date.parse("2014/01/20"), Date.parse("2012/08/17"))
Object {years: 1, months: 5, days: 3}
moment.js can also return human-readable differences ("in a year") if that's what you're really after.
Solution 2:
so this is my function, this receive two dates, do all the work and return a json with 3 values, years, months and days.
varDifFechas = {};
// difference in years, months, and days between 2 datesDifFechas.AMD = function(dIni, dFin) {
var dAux, nAnos, nMeses, nDias, cRetorno
// final date always greater than the initialif (dIni > dFin) {
dAux = dIni
dIni = dFin
dFin = dAux
}
// calculate years
nAnos = dFin.getFullYear() - dIni.getFullYear()
// translate the initial date to the same year that the final
dAux = newDate(dIni.getFullYear() + nAnos, dIni.getMonth(), dIni.getDate())
// Check if we have to take a year off because it is not fullif (dAux > dFin) {
--nAnos
}
// calculate months
nMeses = dFin.getMonth() - dIni.getMonth()
// We add in months the part of the incomplete Yearif (nMeses < 0) {
nMeses = nMeses + 12
}
// Calculate days
nDias = dFin.getDate() - dIni.getDate()
// We add in days the part of the incomplete monthif (nDias < 0) {
nDias = nDias + this.DiasDelMes(dIni)
}
// if the day is greater, we quit the monthif (dFin.getDate() < dIni.getDate()) {
if (nMeses == 0) {
nMeses = 11
}
else {
--nMeses
}
}
cRetorno = {"aƱos":nAnos,"meses":nMeses,"dias":nDias}
return cRetorno
}
DifFechas.DiasDelMes = function (date) {
date = newDate(date);
return32 - newDate(date.getFullYear(), date.getMonth(), 32).getDate();
}
hope this help people looking for a solution.
this is a new version that other guy did, seems to have no erros, hope this works better
Post a Comment for "Obtain Difference Between Two Dates In Years, Months, Days In Javascript"