Obtain difference between two dates in years, months, days in JavaScript [duplicate]

我与影子孤独终老i 提交于 2019-12-12 06:57:10

问题


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 something to calculate, it seems to work, but maybe some expert's here can make corrections or help to make this more simple.


回答1:


You can use moment.js to simplify this:

function difference(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.




回答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.

var DifFechas = {};

// difference in years, months, and days between 2 dates
DifFechas.AMD = function(dIni, dFin) {
    var dAux, nAnos, nMeses, nDias, cRetorno
    // final date always greater than the initial
    if (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 = new Date(dIni.getFullYear() + nAnos, dIni.getMonth(), dIni.getDate())
    // Check if we have to take a year off because it is not full
    if (dAux > dFin) {
        --nAnos
    }
    // calculate months
    nMeses = dFin.getMonth() - dIni.getMonth()
    // We add in months the part of the incomplete Year
    if (nMeses < 0) {
        nMeses = nMeses + 12
        }
    // Calculate days
    nDias = dFin.getDate() - dIni.getDate()
    // We add in days the part of the incomplete month
    if (nDias < 0) {
        nDias = nDias + this.DiasDelMes(dIni)
    }
    // if the day is greater, we quit the month
    if (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 = new Date(date);
    return 32 - new Date(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



来源:https://stackoverflow.com/questions/26311489/obtain-difference-between-two-dates-in-years-months-days-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!