2014-10-11 138 views
-1

好吧,我在这里发现了很多像这样的问题,试图获得年,月和日的两个日期之间的差异......但没有完成我的答案需求。在JavaScript中使用年,月,日两个日期获取差异

所以我写了一些东西来计算,它似乎工作,但也许一些专家在这里可以做出更正或帮助使这更简单。

+0

您应该使用UTC时间/纪元时间 - 从较大的日期减去较短的日期,然后将UTC结果转换回“正常”格式。这是最优雅的方式这个 – 2014-10-11 05:40:44

+0

moment.js或date.js应该处理您的所有需求 – mplungjan 2014-10-11 05:44:07

+0

我写了一个函数在这里。这满足了我的要求,我只是发布这个让解决方案,可以帮助一些寻找这个。谢谢,moment.js不处理这个问题。 date.js我没试过。 – xploshioOn 2014-10-11 05:47:21

回答

2

所以这是我的功能,这接收两个日期,做所有的工作,并返回一个json与3个值,年,月和日。

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(); 
} 

希望这可以帮助寻找解决方案的人。

这是一个新版本的其他人一样,似乎也没有误差修改,希望这个作品更好

+0

这行有错误var mesant = dayssInmonths(until.setmonths(until.getMonth() - 1));' – 2015-06-16 05:40:49

+0

将此转换为'until.setmonths'到这个'until.setMonth' – 2015-06-16 05:41:22

+0

完成@AnikIslamAbhi – xploshioOn 2015-06-16 17:30:12

5

您可以使用moment.js简化此:

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}; 
} 

例如,

> difference(Date.parse("2014/01/20"), Date.parse("2012/08/17")) 
Object {years: 1, months: 5, days: 3} 

如果这就是你真正想要的,moment.js还可以返回人类可读的差异(“在一年中”)。

+0

我不想使用完整的库或插件,如果我只是需要一个功能。 – xploshioOn 2014-10-11 06:28:45